我不想手动将每个映射类添加到 ModelBuilder(),因此尝试使用我有限的反射知识来注册它们。这就是我所拥有的,这是我得到的错误:
代码:
private static ModelBuilder CreateBuilder() {
var contextBuilder = new ModelBuilder();
IEnumerable<Type> configurationTypes = typeof(DatabaseFactory)
.Assembly
.GetTypes()
.Where(type => type.IsPublic && type.IsClass && !type.IsAbstract && !type.IsGenericType && typeof(EntityTypeConfiguration).IsAssignableFrom(type) && (type.GetConstructor(Type.EmptyTypes) != null));
foreach (var configuration in configurationTypes.Select(type => (EntityTypeConfiguration)Activator.CreateInstance(type)))
{
contextBuilder.Configurations.Add(configuration);
}
return contextBuilder;
}
错误: 错误 2 无法从用法中推断方法“System.Data.Entity.ModelConfiguration.Configuration.ConfigurationRegistrar.Add(System.Data.Entity.ModelConfiguration.EntityTypeConfiguration)”的类型参数。尝试明确指定类型参数。 C:\root\development\playground\PostHopeProject\PostHope.Infrastructure.DataAccess\DatabaseFactory.cs 67 17 PostHope.Infrastructure.DataAccess
最佳答案
原答案:
隐含解决方案的详细信息:
上面引用的文章表明,您可以使用 dynamic
关键字绕过编译时类型检查,从而绕过尝试将配置添加到通用 Add()< 的限制
DbModelBuilder
的方法。这是一个快速示例:
// Load all EntityTypeConfiguration<T> from current assembly and add to configurations
var mapTypes = from t in typeof(LngDbContext).Assembly.GetTypes()
where t.BaseType != null && t.BaseType.IsGenericType && t.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>)
select t;
foreach (var mapType in mapTypes)
{
// note: "dynamic" is a nifty piece of work which bypasses compile time type checking... (urgh??)
// Check out: http://msdn.microsoft.com/en-us/library/vstudio/dd264741%28v=vs.100%29.aspx
dynamic mapInstance = Activator.CreateInstance(mapType);
modelBuilder.Configurations.Add(mapInstance);
}
您可以阅读有关使用此关键字的更多信息 on MSDN
关于c# - 为 Entity Framework CPT5 构建 EntityTypeConfiguration 列表的反射(reflection),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4383024/