获取给定的EntityType的导航属性 [英] Get Navigation Properties of given EntityType
问题描述
我使用的 VS2010,EF4.0 。需要像下面的函数。
I am using VS2010, EF4.0. Need function like the following.
private string[] GetNaviProps(Type entityType)//eg typeof(Employee)
{
NorthwindEntities en = new NorthwindEntities();
//here I return all Properties only for example
return entityType.GetProperties().Select(p=>p.Name).ToArray();
//should return Orders,Territories...
}
我已经检查<一href="http://stackoverflow.com/questions/10251863/entity-framework-check-if-%20%20property-is-navigation-property">this,但IObjectContextAdapter似乎什么东西EF6.0和.net4.5。我试图取代它像
I have checked this, but IObjectContextAdapter seems something in EF6.0 and .net4.5. I tried to replace it like
var workspace = en.MetadataWorkspace;
因此,它可以编译,但在3ND线异常抛出即可。
任何帮助?
So it can compile, but exception throw at the 3nd line then.
Any help?
推荐答案
您可以过滤的GetProperties,
结果只拿到这些该实施的ICollection
或的IEnumerable
。但是,你应该记住,字符串
工具的IEnumerable
,所以你必须添加额外的检查不返回字符串
属性。
You can filter GetProperties
results to get only these which implement ICollection
or IEnumerable
. However, you should remember that string
implements IEnumerable
, so you have to add additional check not to return string
properties.
return entityType.GetProperties()
.Where(p => typeof(IEnumerable).IsAssignableFrom(p.PropertyType) && p.PropertyType != string)
.Select(p => p.Name)
.ToArray();
更新
您可以改变你的其中,
predicate比较命名空间为好。它也返回1:1的导航性能:
You can change you Where
predicate to compare namespaces as well. It returns also 1:1 navigation properties:
private static string[] GetNaviProps(Type entityType)//eg typeof(Employee)
{
return entityType.GetProperties()
.Where(p => (typeof(IEnumerable).IsAssignableFrom(p.PropertyType) && p.PropertyType != typeof(string)) || p.PropertyType.Namespace == entityType.Namespace)
.Select(p => p.Name)
.ToArray();
}
这篇关于获取给定的EntityType的导航属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!