簡體   English   中英

EF Fluent API:為從基本抽象類派生的每個實體設置屬性

[英]EF Fluent API: Set property for each entity derived from a base abstract class

我有一個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);
}

但是不會編譯,因為

“實體是一個變量,但就像一個類型一樣使用”。

我想到了:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM