簡體   English   中英

構建實體框架CPT5的EntityTypeConfiguration列表的思考

[英]Reflection to build list of EntityTypeConfiguration for Entity Framework CPT5

我不想手動將每個映射類添加到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的通用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);
}

您可以在MSDN上閱讀有關使用此關鍵字的更多信息

您的var configurationType ,它不是EntityTypeConfiguration類型。 您必須為Add方法提供EntityTypeConfiguration的實例,可能基於您當前的類型: configuration

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM