Entity Framework Core, setting common property for all Entites in one go

ef-fluent-api entity-framework entity-framework-core

Question

How can someone set a value for a prop on all entities without having to do so explicit

I have this base

 public abstract class Base<TKey>
    {
        public TKey Id { get; private set; }
        public DateTime CreatedOn { get; private set; }
    }

from which all other entities derive from. As you can see it has 2 fields, I would like to know how to set DateTime in one go without having to add this line of coude for each entity

    modelBuilder.Entity<MyEntity111>().Property(prop => prop.CreatedOn).HasDefaultValue(DateTime.UtcNow).IsRequired();
1
0
9/26/2018 10:04:26 AM

Popular Answer

So using @viveknuna suggestion on this post EF Core 2.1.1 how to ignore some properties when entity implements some specific interface

I've created this extension method on top of ModelBuilder

internal static partial class ModelBuilderExtensions
{
    private static ModelBuilder _builder;

    internal static ModelBuilder InitializeBuilder(this ModelBuilder modelBuilder)
    {
        _builder = modelBuilder;

        IEnumerable<string> properties = typeof(DataEntity<>).GetProperties().Select(propInfo => propInfo.Name);

        IEnumerable<IMutableEntityType> entities = modelBuilder.Model.GetEntityTypes();

        foreach (IMutableEntityType entity in entities)
        {
            EntityTypeBuilder entityTypeBuilder = modelBuilder.Entity(entity.ClrType);

            foreach (string propriety in properties)
            {
                entityTypeBuilder.Property("CreatedOn").HasDefaultValue(DateTime.UtcNow);
                entityTypeBuilder.Property("Id").ValueGeneratedOnAdd();
            }
        }

        return _builder;
    }
}

usage :

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder
        .InitializeBuilder();
}
0
9/26/2018 12:25:43 PM


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