获取给定EntityType的导航属性 [英] Get Navigation Properties of given EntityType

查看:119
本文介绍了获取给定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...
}

我有检查,但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;

所以它可以编译,但异常抛在第三行然后。

任何帮助?

So it can compile, but exception throw at the 3nd line then.
Any help?

推荐答案

您可以过滤 GetProperties 它实现 ICollection IEnumerable 。但是,您应该记住, string 实现 IEnumerable ,因此您必须添加额外的检查才能返回 string 属性。

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

更新

您可以更改 where 谓词来比较命名空间。它还返回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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆