我不想将每个映射类都手动添加到ModelBuilder()中,因此尝试使用有限的反射知识来注册它们。这就是我所拥有的,这就是我得到的错误:
CODE:
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
最佳答案
原始答案:
http://areaofinterest.wordpress.com/2010/12/08/dynamically-load-entity-configurations-in-ef-codefirst-ctp5/
隐含解决方案的详细信息:
上面引用的文章显示,可以使用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/