Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better handling of default value in inherited Base entity in DbContext #27341

Closed
SidusCaelum opened this issue Feb 2, 2022 · 1 comment
Closed

Comments

@SidusCaelum
Copy link

Is there a better way to handle a base entity inheritance in a context class for shared properties? Specifically if you have a base with createdAt and updatedAt, I find that I have to manually add a HasDefaultValueSql for both properties on each table. I am using ef6 and npgsql for my db connection.

.NET 6
EF Core version 6.0.1
npgsql 6.0.3

DbContext.cs

    protected override void OnModelCreating(ModelBuilder mb)
    {
        mb.Entity<User>()
            .Property(p => p.CreatedAt)
            .HasDefaultValueSql("now()");
        mb.Entity<User>()
            .Property(p => p.UpdatedAt)
            .HasDefaultValueSql("now()");
        mb.Entity<Workout>()
            .Property(p => p.CreatedAt)
            .HasDefaultValueSql("now()");
        mb.Entity<Workout>()
            .Property(p => p.UpdatedAt)
            .HasDefaultValueSql("now()");
        mb.Entity<Exercise>()
            .Property(p => p.CreatedAt)
            .HasDefaultValueSql("now()");
        mb.Entity<Exercise>()
            .Property(p => p.UpdatedAt)
            .HasDefaultValueSql("now()");
        mb.Entity<Set>()
            .Property(p => p.CreatedAt)
            .HasDefaultValueSql("now()");
        mb.Entity<Set>()
            .Property(p => p.UpdatedAt)
            .HasDefaultValueSql("now()");

        base.OnModelCreating(mb);
    }

Base.cs

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace SudorNET.Db.Models;

public abstract record Base
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public int Id { get; set; }

    public DateTime CreatedAt { get; set; }

    public DateTime UpdatedAt { get; set; }
}
@ajcvickers
Copy link
Member

@SidusCaelum Duplicate of #6787. Make sure to vote (👍) for that issue.

@ajcvickers ajcvickers reopened this Oct 16, 2022
@ajcvickers ajcvickers closed this as not planned Won't fix, can't repro, duplicate, stale Oct 16, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants