c# - 为 Entity Framework CPT5 构建 EntityTypeConfiguration 列表的反射(reflection)

标签 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;
        }

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

相关文章:

c# - 如何将连续按键发送到程序?

c# - 如何为 Azure Functions 配置客户特定的 API key

c# - Entity Framework C# 中的反射

asp.net-mvc-3 - 日期字段给出验证所需的错误

c# - 组合框和 Entity Framework

c# - Entity Framework 正确使用连接表?

c# - Streamreader 和 StackOverflowException

c# - 显示hadoop内容C#

go - 如何通过读取设置文件在 Golang 中动态创建结构?

java - 创建编译时未知的类的实例