我正在使用实体框架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个实体。有没有更简单的方法可以做到这一点?
发布于 2015-12-20 22:26:23
是的,有。
选项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(); });
}
}我创建了一个泛型的表方法,它告诉EF to MapInheritedProperties to MapInheritedProperties是泛型类型。
在使用反射之后,我们从当前类获得这个方法,然后我们查找从MainObj继承的所有类型,对于每一个我们调用MapInheritedProperties的类型,然后魔术就完成了。
https://stackoverflow.com/questions/34379961
复制相似问题