簡體   English   中英

使用Entity Framework 6中的自定義約定控制列映射

[英]Controlling column mapping with a custom convention in Entity Framework 6

我有一個類TypeEntity ,它將作為幾十個實體的基類。 我正在使用TPC,所以我需要將基類的所有屬性映射到具有類具體類名稱的表,並將Key字段設置為數據庫生成。

目前我正在使用EntityTypeConfiguration為每個實體類型執行此操作,如下所示:

class LineItemType : EntityTypeConfiguration<Models.LineItemType>
{
    public LineItemType()
    {
        this.Property(e => e.Key)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        this.Map(e => e.MapInheritedProperties()
                       .ToTable(nameof(LineItemType)));
    }
}

這工作正常,但非常重復。 我必須記住為從TypeEntity繼承的每個類型創建配置類,設置鍵,並映射繼承的屬性。 這似乎是定制Convention的理想案例。


我創建了一個TypeEntityTpcConvention Convention ,如下所示:

class TypeEntityTpcConvention : Convention
{
    public TypeEntityTpcConvention()
    {
        this.Types<TypeEntity>()
            .Configure(e => e.Property(p => p.Key)
                             .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity));
    }
}

哪個用於將Key設置為生成的數據庫,但我無法找到任何方法來訪問約定內的屬性的表映射。


理想情況下,我希望這樣的事情:

this.Types<TypeEntity>()
    .Configure(e => e.MapInheritedProperties()
    .ToTable(e.ClrType.Name));

或者甚至對每個需要映射的屬性進行這樣的調用:

this.Types<TypeEntity>()
    .Configure(e => e.Property(p=>p.Key)
                     .ToTable(e.ClrType.Name));

這兩者似乎都不存在。 我有什么方法可以控制Convention內部屬性的映射?


經過一些額外的研究,看起來有更多高級的約定選項可用作IStoreModelConventionIConceptualModelConvention ,但是有關如何使用它們的有用文檔非常缺乏。 幾個小時用斷點和觀察窗口戳它們之后,我還沒想出如何使用這些接口來控制列映射。


我目前的解決方案是使用反射來查找在OnModelCreating中繼承自TypeEntity所有類型,並將屬性映射到正確的表。 這是有效的,但我更願意使用一個約定,如果可能的話,因為這看起來像是為了制定約定的東西。 我覺得我錯過了一些明顯的東西。

據我所看到的,你可以只寫在類型配置OnModelCreating你的方法DbContext ,它是非常相似,你已經在問題中提到的代碼。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Types<TypeEntity>().Configure(c =>
    {
        c.HasKey(p => p.Key);
        // probably not needed, but won't do any harm
        c.Property(p => p.Key).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        c.ToTable(c.ClrType.Name);
    });
}

如果這種方法有任何問題,請告訴我,我將重新訪問該主題。

編輯:

完全相同的原則可以應用於約定:

class TypeEntityConvention : Convention
{
    public TypeEntityConvention()
    {
        this.Types<TypeEntity>().Configure(c =>
        {
            c.HasKey(p => p.Key);
            c.Property(p => p.Key).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            c.ToTable(c.ClrType.Name);
        });
    }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Conventions.Add<TypeEntityConvention>();
}

暫無
暫無

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

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