构建实体框架CPT5的EntityTypeConfiguration列表的思考

Pau*_*aul 6 c# reflection entity-framework-4

我不想手动将每个映射类添加到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;
        }
Run Code Online (Sandbox Code Playgroud)

错误: 错误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

小智 12

原始答案:

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);
}
Run Code Online (Sandbox Code Playgroud)

您可以在MSDN上阅读有关使用此关键字的更多信息