EF Fluent API: set a property for each object derived from a base abstract class

I have a BaseClass that is abstract and has many abstract properties.

I have a dozen or so (they probably grow) entities that are part of the Entity Framework, each of which is derived from BaseClass.

I try to avoid the need:

modelBuilder.Entity<Entity1>().HasKey(t => t.Id);
modelBuilder.Entity<Entity2>().HasKey(t => t.Id);
modelBuilder.Entity<Entity3>().HasKey(t => t.Id);
...

for each property and each object, as this seems very wasteful and creates a lot of code duplication. I experimented with getting all Entities in the namespace that come from BaseClass:

var derivedEntities = Assembly.GetExecutingAssembly().GetTypes().
                Where(t => t.Namespace == "My.Entities" && t.IsAssignableFrom(typeof(BaseClass)));

However, the following logical steps:

foreach (var entity in derivedEntities)
{
    modelBuilder.Entity<entity>().HasKey(t => t.Id);
}

but will not compile because

"entity is a variable, but used as a type."

+4
1

:

public class BaseObjectConfiguration<TEntity> : EntityTypeConfiguration<TEntity>
        where TEntity : BaseObject
{
        public BaseObjectConfiguration()
        {
            // Mapped
            HasKey(t => t.Id);
            Property(t => t.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            Property(t => t.Name).IsRequired().HasMaxLength(100);
            Property(t => t.DisplayName).IsOptional().HasMaxLength(100);
            Property(t => t.Alias).IsOptional().HasMaxLength(100);
            Property(t => t.SourceId).IsRequired();
            Property(t => t.AccessLevel).IsRequired();
            Property(t => t.CreatedOn).IsOptional();
            Property(t => t.CreatedBy).IsOptional().HasMaxLength(50);
            Property(t => t.ModifiedOn).IsOptional();
            Property(t => t.ModifiedBy).IsOptional().HasMaxLength(50);

            //// Base Entity Ignores (Not Mapped)
            Ignore(t => t.SomeIgnoredProperty);
            Ignore(t => t.SomeIgnoredProperty2);
            Ignore(t => t.SomeIgnoredProperty3);
        }
}

OnModelCreating DbContext:

modelBuilder.Configurations.Add(new BaseObjectConfiguration<Entity1>());
modelBuilder.Configurations.Add(new BaseObjectConfiguration<Entity2>());
modelBuilder.Configurations.Add(new BaseObjectConfiguration<Entity3>());
modelBuilder.Configurations.Add(new BaseObjectConfiguration<Entity4>());
...

// Specific mappings options for each entity:
modelBuilder.Entity<Entity1>().HasRequired(t => t.NodeTypeEntity).
                WithMany(t => t.Nodes).HasForeignKey(t => t.NodeTypeId);
            modelBuilder.Entity<NWatchNode>().HasOptional(t => t.Parent).
                WithMany(t => t.Children).HasForeignKey(t => t.ParentId);
...
+5

Source: https://habr.com/ru/post/1609862/


All Articles