2016-04-14 14 views
0

すべてのエンティティ(モデル)を取得しようとしていて、タイプがICollectionのナビゲーションプロパティのみを取得しようとしていますが、これは動作していないように見えます。すべてのエンティティを取得してナビゲーションプロパティを取得

foreach (var propertyInfo in new CompanyDBContext().GetType() 
        .GetProperties(
          BindingFlags.Public 
          | BindingFlags.Instance)) 
{ 
    Console.WriteLine(propertyInfo.Name); 

    //var entity = DbSet<propertyInfo.Name> 
} 

私は上記のコードを使用しているすべてのモデルを取得することができていますが、どのように私は次のICollectionタイプであるすべてのナビゲーションプロパティを取得できますか?

+0

これまでに、これまでに質問されています。http://stackoverflow.com/questions/17886725/ef5-how-to-get-list-of-navigation-propeドメインオブジェクト用 –

+0

@WicherVisserはい、すでにエンティティを持っていますが、propertyInfoを持っているのでpropertyInfoをオブジェクトに変換する方法がわからないので、ICollectionsのみを選択する方法もわかりません – Mathematics

+0

作成PropertyInfoを使用するタイプのインスタンスも前に実行されています:http://stackoverflow.com/questions/15641339/create-new-propertyinfo-object-on-the-fly –

答えて

1

まず、すべてのエンティティのタイプをDbContextから取得する必要があります。 DbSet<>のタイプのプロパティは、DbContextに定義されていますが、実際にはエンティティを囲んでいます。あなたは代わりにそれをつかむ必要があります。

private static readonly Type DbSetType = typeof(DbSet<>); 
private static IEnumerable<Type> GetAllEntityTypes(Type contextType) 
{ 
    return contextType.GetProperties(BindingFlags.Public | BindingFlags.Instance) 
     .Select(p => p.PropertyType) 
     .Where(t => t.IsGenericType && t.GetGenericTypeDefinition() == DbSetType) 
     .Select(t => t.GetGenericArguments()[0]); 
} 

そしてここで、Entityタイプからナビゲーションプロパティを取得するためのhttps://stackoverflow.com/a/27124251/2509344

private static readonly MethodInfo CreateObjectSetMethodInfo = typeof(ObjectContext).GetMethod("CreateObjectSet", new Type[0]); 
private static readonly Type CollectionType = typeof(ICollection<>); 
private static IEnumerable<PropertyInfo> GetNavigationProperties(DbContext context, Type entityType) 
{ 
    var objectContext = ((IObjectContextAdapter)context).ObjectContext; 
    var createObjectSetMethod = CreateObjectSetMethodInfo.MakeGenericMethod(entityType); 
    var entity = createObjectSetMethod.Invoke(objectContext, new object[0]); 

    var entitySet = (EntitySet)entity.GetType().GetProperty("EntitySet").GetValue(entity); 
    var elementType = entitySet.ElementType; 
    return elementType.NavigationProperties.Select(p => entityType.GetProperty(p.Name)) 
     // Filter Properties that are of type ICollection 
     .Where(p => p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == CollectionType); 
} 

のバージョンを変更され、最終的にDbContext内で定義されたエンティティのすべてのナビゲーションプロパティを取得するためのヘルパーメソッドです:

var context = new CompanyDBContext(); 
var entities = GetAllEntityTypes(context.GetType()); 
foreach (var entity in entities) 
{ 
    var navigationProperties = GetNavigationProperties(context, entity).ToList(); 
} 
関連する問題