您必須先從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();
}
這已經問過,在這裏:http://stackoverflow.com/questions/17886725/ef5-how-to-get-list-of-navigation-prope rties-for-a-domain-object –
@WicherVisser是的,但他們已經有實體,因爲我有propertyInfo,我不知道如何將propertyInfo轉換爲對象,我也不確定如何僅選擇ICollections – Mathematics
創建使用PropertyInfo的類型的實例也已在之前完成:http://stackoverflow.com/questions/15641339/create-new-propertyinfo-object-on-the-fly –