我需要在 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/