2016-04-14 65 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 rties-for-a-domain-object –

+0

@WicherVisser是的,但他們已經有實體,因爲我有propertyInfo,我不知道如何將propertyInfo轉換爲對象,我也不確定如何僅選擇ICollections – Mathematics

+0

創建使用PropertyInfo的類型的實例也已在之前完成:http://stackoverflow.com/questions/15641339/create-new-propertyinfo-object-on-the-fly –

回答

1

您必須先從DbContext獲取所有實體的類型。在DbContext內定義的DbSet<>類型的任何屬性實際上都包含一個實體。你需要取而代之。

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