簡體   English   中英

實體框架tpc繼承模型創建

[英]Entity Framework tpc inheritance model creating

我正在使用Entity Framework 6和TPC繼承策略

我對每個實體的基類如下:

public class MainObj : IdentifiedModel
{
    public int Status
    {
        get;
        set;
    }

    public string OType
    {
        get;
        set;
    }

    public DateTime Date { get; set; }
}

這是我的模型創建代碼:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        modelBuilder.Entity<User>().Map(m =>
        {
            m.MapInheritedProperties();
            m.ToTable("User");
        });

        modelBuilder.Entity<Entity2>().Map(m =>
        {
            m.MapInheritedProperties();
            m.ToTable("Entity2");
        });

        modelBuilder.Entity<Entity3>().Map(m =>
        {
            m.MapInheritedProperties();
            m.ToTable("Entity3");
        });

        modelBuilder.Entity<Entity4>().Map(m =>
        {
            m.MapInheritedProperties();
            m.ToTable("Entity4");
        });

        base.OnModelCreating(modelBuilder);
} 

如您所見,我正在使用名稱映射每個實體,並且我有200個實體。 有沒有更簡單的方法可以做到這一點?

就在這里。

選項1

如果您不需要MainObj類成為表,則只需使其抽象並刪除將表名復數的約定,如下所示:

public abstract class MainObj
{
    public int Status { get; set; }

    public string OType { get; set; }

    public DateTime Date { get; set; }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    //base.OnModelCreating(modelBuilder); you dont need this line, it does nothing
}

選項2

如果MainObj必須是一個表,則可以使用反射為您做映射,並刪除使表名復數的約定,如下所示:

public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        var methodInfo = GetType().GetMethod("MapInheritedProperties");

        var type = typeof(MainObj);
        foreach (var descendantType in type.Assembly.GetTypes().Where(t => t.IsAssignableFrom(type)))
        {
            var mapInheritedProperties = methodInfo.MakeGenericMethod(descendantType);
            mapInheritedProperties.Invoke(null, new object[] { modelBuilder });
        }

        //base.OnModelCreating(modelBuilder); you dont need this line, it does nothing
    }

    private static void MapInheritedProperties<T>(DbModelBuilder modelBuilder) where T : class
    {
        modelBuilder.Entity<T>().Map(m => { m.MapInheritedProperties(); });
    }
}

我創建了一個通用的MapInheritedProperties方法,該方法告訴EF將MapInheritedProperties傳遞給屬於通用類型的表。

使用反射后,我們從當前類中獲得此方法,然后查找從MainObj繼承的所有類型,對於每個類型,我們將其稱為MapInheritedProperties,然后魔術就完成了。

暫無
暫無

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

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