首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >实体框架tpc继承模型创建

实体框架tpc继承模型创建
EN

Stack Overflow用户
提问于 2015-12-20 18:21:11
回答 1查看 114关注 0票数 0

我正在使用实体框架6和TPC继承策略。

我的每个实体的基类如下:

代码语言:javascript
复制
public class MainObj : IdentifiedModel
{
    public int Status
    {
        get;
        set;
    }

    public string OType
    {
        get;
        set;
    }

    public DateTime Date { get; set; }
}

这是我创建代码的模型:

代码语言:javascript
复制
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个实体。有没有更简单的方法可以做到这一点?

EN

回答 1

Stack Overflow用户

发布于 2015-12-20 22:26:23

是的,有。

选项1

如果您不需要MainObj类成为一个表,那么只需将其设为抽象,并移除一个将表名复数形式的约定,就像这样:

代码语言:javascript
复制
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必须是一个表,那么您可以使用反射为您做映射工作,并删除表名为复数的约定,如下所示:

代码语言:javascript
复制
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(); });
    }
}

我创建了一个泛型的表方法,它告诉EF to MapInheritedProperties to MapInheritedProperties是泛型类型。

在使用反射之后,我们从当前类获得这个方法,然后我们查找从MainObj继承的所有类型,对于每一个我们调用MapInheritedProperties的类型,然后魔术就完成了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34379961

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档