2010-12-08 4 views
5

リフレクションの限られた知識を使用して登録するために、各マッピングクラスを手動でModelBuilder()に追加する必要はありません。これは私が持っているものであり、これは私が取得していますエラーです:Entity Framework CPT5のEntityTypeConfigurationのリストを作成するためのリフレクション

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

ERROR: エラーメソッドの型引数2「System.Data.Entity.ModelConfigurationを.Configuration.ConfigurationRegistrar.Add(System.Data.Entity.ModelConfiguration.EntityTypeConfiguration) 'を使用から推測することはできません。型引数を明示的に指定してみてください。 C:\ルート\開発\遊び場PostHopeProject \ PostHope.Infrastructure.DataAccess \ DatabaseFactory.cs \ 67 17 PostHope.Infrastructure.DataAccess

答えて

11

オリジナルの答え:

http://areaofinterest.wordpress.com/2010/12/08/dynamically-load-entity-configurations-in-ef-codefirst-ctp5/

暗黙のソリューションの詳細:

上記の参照資料では、時の型チェックをコンパイルバイパスするdynamicキーワードを使用できることを示しており、したがって、の汎用Add()メソッドに構成を追加しようとする制限が回避されます。

// 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

の使用方法の詳細を読むことができます:ここでは簡単のサンプルです
1

あなたvar configurationはタイプEntityTypeConfigurationのされていない、タイプTypeです。 AddメソッドのインスタンスはEntityTypeConfiguration(おそらく現在のタイプ:configuration)にする必要があります。

関連する問題