EF Fluent API:为从基本抽象类派生的每个实体设置属性

时间:2015-10-01 21:45:11

标签: c# .net entity-framework ef-fluent-api

我有一个BaseClass,它是抽象的,并且有许多抽象属性。

我有十几个(可能会增长)实体,它们是Entity Framework的一部分,每个实体都派生自BaseClass。

我试图避免这样做:

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

对于每个属性和每个实体,因为这看起来非常浪费并且会产生大量的代码重复。我尝试通过以下方式获取从BaseClass派生的名称空间中的所有实体:

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

然而,接下来的逻辑步骤似乎是:

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

但不会编译,因为

  

&#34;实体是一个变量,但用作类型&#34;。

1 个答案:

答案 0 :(得分:6)

我明白了:

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);
        }
}

然后,在DbContext内部的OnModelCreating中:

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);
...