[英]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个实体。 有没有更简单的方法可以做到这一点?
就在这里。
如果您不需要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
}
如果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.