0

I have a one entity named User that herency from Base class.

Base.cs

public class Base
{
    public string Id { get; set; } = Guid.NewGuid().ToString();

    public bool Active { get; set; } = true;

    public string CreatedBy { get; set; } = default!;

    public string DeletedBy { get; set; } = default!;

    public string UpdatedBy { get; set; } = default!;

    public bool IsDeleted { get; set; } = false;

    public DateTime CreatedAt { get; set; } = DateTime.Now;

    public DateTime? UpdatedAt { get; set; }

    public DateTime? DeletedAt { get; set; }
}

User.cs

public class User : Base
{
    public string Name { get; set; } = default!;

    public string Password { get; set; } = default!;

    public ICollection<EmailAccount> EmailAccounts { get; set; } = default!;
}

I tried set default value of this way:

public DateTime CreatedAt { get; set; } = DateTime.Now;

but it's not working.

Reading docs I find a way to do this.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>()
        .Property(u => u.CreatedAt)
        .HasDefaultValueSql("getdate()");
}

But not working for me because I will create all entities its herency from Base class and I'll need to do this for each entity.

Is there any way of doing this?

  • Although you will still have to add a line of code in your configurations, it will be only one and you can configure everything about the base class https://stackoverflow.com/questions/49990365/entity-framework-core-2-0-how-to-configure-abstract-base-class-once – spyros__ Feb 05 '23 at 12:26

0 Answers0