In my OnModelCreating
我的数据上下文的方法目前正在手动映射所有实体配置映射类,例如:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new UserMap());
// 20 or so mapping configuration below
}
我想通过使用反射来简化这个过程,所以我有以下代码:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// Find all EntityTypeConfiguration classes in the assembly
foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
foreach (Type t in asm.GetTypes())
if (t.IsDerivedFromOpenGenericType(typeof(EntityTypeConfiguration<>)))
modelBuilder.Configurations.Add(Activator.CreateInstance(t));
}
the IsDerivedFromOpenGenericType
来自这个问题 https://stackoverflow.com/questions/6426949/how-can-i-use-reflection-to-return-all-classes-subclassing-from-a-generic-withou并且工作正常。
问题是这无法编译,因为Activator.CreateInstance(t)
返回一个object
,但模型构建者期望System.Data.Entity.ModelConfiguration.ComplexTypeConfiguration<TComplexType>
.
通常当使用Activator
类我只是将对象转换为我期望的类型t
(或者我期望该类采取什么),但由于这是使用泛型,我不知道有什么方法可以做到这一点。
有人有什么想法吗?
我不知道为什么这个信息这么难找到(至少对我来说是这样),但是有一个更简单的方法可以详细地做到这一点here http://patrickdesjardins.com/blog/how-to-register-model-builder-without-having-to-manually-add-them-one-by-one.
public class MyDbContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.AddFromAssembly(Assembly.GetAssembly(GetType())); //Current Assembly
base.OnModelCreating(modelBuilder);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)