Entity Framework Core 2.0 default value for common property in many tables

asp.net-core-2.0 entity-framework-core

Question

I am doing code first EF Core 2.0 migrations. I have few columns which are common across all entities. All entities inherit this class as shown below.

How do I set the default value for CreateDate as current date, CreateBy as 'System' and IsDeleted as 0?

public class BaseEntity
{
    public DateTime CreateDate { get; set; }

    public string CreateBy { get; set; }

    public bool IsDeleted { get; set; }
}

I know how to do this for a single property. ie.

class MyContext : DbContext
{
    public DbSet<CaseDetails> CaseDetails{ get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<CaseDetail>()
            .Property(b => b.CreateDate)
            .HasDefaultValueSql("getutcdate()");

        modelBuilder.Entity<CaseDetail>()
            .Property(b => b.CreateBy)
            .HasDefaultValue("System");

        modelBuilder.Entity<CaseDetail>()
            .Property(b => b.IsDeleted)
            .HasDefaultValue("0()");
    }
}

Can anyone help me how to do this in an efficient way so it will be available for all entities?

Thanks

1
3
1/10/2018 12:03:32 PM

Accepted Answer

Correct way with latest version of net.core 2.0:

    foreach (var entityType in builder.Model.GetEntityTypes()
        .Where(e => typeof(Entity<int>).IsAssignableFrom(e.ClrType)))
    {
        builder
            .Entity(entityType.ClrType)
            .Property("CreatedDate")
            .HasDefaultValueSql("getutcdate()");
    }
2
2/8/2018 11:54:37 AM

Popular Answer

Here is one way to do it.

foreach (var entityType in modelBuilder.Model.GetEntityTypes()
    .Where(t => t.ClrType.IsSubclassOf(typeof(BaseEntity))))
{
    modelBuilder.Entity(
        entityType.Name,
        x =>
        {
            x.Property("CreateDate")
                .HasDefaultValueSql("getutcdate()");

            x.Property("CreateBy")
                .HasDefaultValue("System");

            x.Property("IsDeleted")
                .HasDefaultValue(false);
        });
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow