[英]EF Fluent API: Set property for each entity derived from a base abstract class
I have a BaseClass, which is abstract, and has many abstract properties. 我有一个BaseClass,它是抽象的,并且有许多抽象属性。
I have a dozen or so (it will probably grow) entities that are part of the Entity Framework that each derive from BaseClass. 我有十几个(可能会增长)实体,它们是Entity Framework的一部分,每个实体都派生自BaseClass。
I'm trying to avoid having to do: 我试图避免不得不这样做:
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 entity, since that seems very wasteful and creates a lot of code duplication. 对于每个属性和每个实体,因为这看起来非常浪费并且会产生大量的代码重复。 I experimented with getting all the Entities in a namespace that derive from the BaseClass by:
我尝试通过以下方式获取从BaseClass派生的名称空间中的所有实体:
var derivedEntities = Assembly.GetExecutingAssembly().GetTypes().
Where(t => t.Namespace == "My.Entities" && t.IsAssignableFrom(typeof(BaseClass)));
However, the next logical steps seems to be: 但是,接下来的逻辑步骤似乎是:
foreach (var entity in derivedEntities)
{
modelBuilder.Entity<entity>().HasKey(t => t.Id);
}
but will not compile, because 但是不会编译,因为
"entity is a variable, but is used like a type".
“实体是一个变量,但就像一个类型一样使用”。
I figured it out: 我想到了:
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);
}
}
Then, in OnModelCreating inside of the DbContext: 然后,在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);
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.