c# - EntityType' 是一个变量,但在使用反射时像类型一样使用

标签 c# reflection entity-framework-6

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

我创建了一个extension 用于使用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' is a variable but is used like a type

在这一行中:

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

有什么问题吗?我该如何解决这个问题???

最佳答案

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

This method is provided as a convenience to allow entity types to be registered dynamically without the need to use MakeGenericMethod in order to call the normal generic Entity method.

所以而不是 builder.Entity<EntityType>();你会改用 builder.RegisterEntityType(EntityType);

值得一提的是,在这种情况下,通常有一种非泛型方法采用 Type object 而不是对象,所以如果您以后发现自己在使用其他软件时遇到这种情况,请使用 Type 检查该非通用方法。参数。

关于c# - EntityType' 是一个变量,但在使用反射时像类型一样使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55472336/

相关文章:

c# - Xamarin Native 中 AcquireTokenAsync 和 LoginAsync 之间的差异

java - 我是否会在使用 PhantomReferences 完成时避免使用反射?

java - 方法在反射中有效,但在 Java 中的 "normal way"中无效

C# : How to pause the thread and continue when some event occur?

c# - ProtectedData.Protect (DPAPI) 有多安全?

c# - 如何裁剪部分gif图像?

.net - 泛型类型和泛型类型定义之间有什么区别?

c# - 在 Entity Framework 中显式加载嵌套相关模型

c# - Entity Framework - CommitFailureHandler.ClearTransactionHistory()

c# - 标识为 [x] 的项目已存在于元数据集合中。我该如何解决?