如何通过反射加载所有Entity Framework 4.1实体配置实体? [英] How can I load all Entity Framework 4.1 entity configuration entities via reflection?

查看:98
本文介绍了如何通过反射加载所有Entity Framework 4.1实体配置实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在用于数据上下文的 OnModelCreating 方法中,我当前正在手动映射所有实体配置映射类,例如:

In my OnModelCreating method for my data context I currently am manually mapping all my entity configuration mapping classes manually, like:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new UserMap());
    // 20 or so mapping configuration below
}

我想简化通过使用反射,所以我有以下代码:

I want to streamline this by using reflection, so I have the following code:

    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));   
    }

IsDerivedFromOpenGenericType 是来自此问题并正常工作。

问题在于,由于 Activator.CreateInstance(t),因此无法编译返回对象,但是模型构建器期望使用 System.Data.Entity.ModelConfiguration.ComplexTypeConfiguration< TComplexType>

The problem is this doesn't compile because Activator.CreateInstance(t) returns an object, but the model builder is expecting a System.Data.Entity.ModelConfiguration.ComplexTypeConfiguration<TComplexType>.

通常在使用 Activator 类时,我只会将对象转换为我期望的类型 t 是(或我希望班级接受),但是由于这是使用泛型,所以我不知道这样做的方法。

Normally when using the Activator class I would just cast the object as whatever I expect type t to be (or what I expect the class to take), but since this is using a generics I don't know of a way to do that.

有人有什么想法吗?

推荐答案

我不确定为什么很难找到此信息(至少对我而言),但是有一种更简单的方法来进行详细操作此处

I'm not sure why this information is so hard to find (at least it was for me), but there is a much simpler way to do it detailed here.

public class MyDbContext : DbContext
{
  protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
    modelBuilder.Configurations.AddFromAssembly(Assembly.GetAssembly(GetType())); //Current Assembly
    base.OnModelCreating(modelBuilder);
  }
}

这篇关于如何通过反射加载所有Entity Framework 4.1实体配置实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆