【问题标题】:EntityType' is a variable but is used like a type when use the ReflectionEntityType' 是一个变量,但在使用反射时像类型一样使用
【发布时间】:2019-04-02 19:19:00
【问题描述】:

我需要在DbContext注册所有实体。

我创建了一个extention 用于使用Reflection 自动注册所有实体:

  public static void RegisterAllEntity<BaseType>(this DbModelBuilder builder, params Assembly[] assmblies)
    {
        IEnumerable<Type> types = assmblies.SelectMany(x => x.GetExportedTypes())
            .Where(x => x.IsClass && !x.IsAbstract && x.IsPublic && typeof(BaseType).IsAssignableFrom(x));

        foreach (Type EntityType in types)
            builder.Entity<EntityType>();
    }

但它告诉我这个错误:

EntityType' 是一个变量,但用作类型

在这一行:

    foreach (Type EntityType in types)
            builder.Entity<EntityType>();

有什么问题?这个问题怎么解决???

【问题讨论】:

  • 您将运行时Type 对象与编译时类型混合在一起,您需要Entity 的重载,它接受类型object
  • @thisextendsthat 请进一步指导我。我该怎么做?
  • 你可以在这里找到东西stackoverflow.com/questions/44207451/…
  • @RedaTaha 我看到了,但它没有回答我

标签: c# reflection entity-framework-6


【解决方案1】:

查看文档我认为您想使用DbModelBuilder.RegisterEntityType 而不是DbModelBuilder.Entity。前者的文档说:

提供此方法是为了方便动态注册实体类型,而无需使用 MakeGenericMethod 来调用普通的通用实体方法。

所以你应该使用builder.RegisterEntityType(EntityType);而不是builder.Entity&lt;EntityType&gt;();

值得一提的是,在这种情况下,通常有一个非泛型方法采用 Type 对象,因此如果您发现自己在这种情况下使用其他软件,请使用以下命令检查该非泛型方法Type 参数。

【讨论】:

    【解决方案2】:

    你在foreach循环中使用EntityType作为变量,在builder.Entity&lt;EntityType&gt;()中使用EntityType作为类型。例如,将变量名称从 EntityType 更改为 entityType,以便 C# 编译器可以理解您的代码

    【讨论】:

      【解决方案3】:

      通用参数需要在编译期间可解析。您需要使用反射在这样的循环中调用Entity 方法。请查看this anwser。

      使用示例

      ...
      MethodInfo method = typeof(DbModelBuilder).GetMethod("Entity");
      MethodInfo generic = method.MakeGenericMethod(EntityType);
      generic.Invoke(builder, null);
      

      编辑:

      和Chris mentioned一样,不需要使用反射,因为DbModelBuilder提供了RegisterEntityType方法,它接受Type作为参数,例如:

      builder.RegisterEntityType(EntityType);
      

      EDIT2:克里斯的answer

      【讨论】:

      • 无需使用反射 - DBModelBuilder 提供了一个方法 (RegisterEntityType),它接受 Type 作为参数并明确表示它的存在允许您在不需要使用 MakeGenericMethod 的情况下注册事物。
      猜你喜欢
      • 2013-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-17
      相关资源
      最近更新 更多