我在用VS2010、EF4.0。需要如下功能。
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...
}
我检查过this https://stackoverflow.com/questions/10251863/entity-framework-check-if-%20%20property-is-navigation-property,但 IObjectContextAdapter 似乎是 EF6.0 和 .net4.5 中的东西。我尝试像这样替换它
var workspace = en.MetadataWorkspace;
所以它可以编译,但是在第三行抛出异常。
有什么帮助吗?
您可以过滤GetProperties
结果只得到那些实现ICollection
or IEnumerable
。然而,你应该记住这一点string
实施IEnumerable
,所以你必须添加额外的检查才能不返回string
特性。
return entityType.GetProperties()
.Where(p => typeof(IEnumerable).IsAssignableFrom(p.PropertyType) && p.PropertyType != string)
.Select(p => p.Name)
.ToArray();
Update
你可以改变你Where
还可以使用谓词来比较命名空间。它还返回 1:1 导航属性:
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();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)