如何通过检索表对象属性获取父表和子表?

时间:2014-06-18 17:54:29

标签: asp.net linq linq-to-sql linq-to-entities linqpad

我有下面的代码,它用来拉对象"申请人" (表申请人)财产。

void Main()
{
        PropertyInfo[] props = typeof(Applicant).GetProperties();
        foreach (PropertyInfo prop in props)
        {
            prop.Name.Dump();
        }
}

结果是:

EthnicBackground
Distance
TransplantHospital
Appointments
Employers
Claims

EthnicBackground,Distance,TransplantHospital是申请人的父表。

约会,雇主,索赔是申请人的儿子表。

现在结果是父表和子表混合在一起。

如何修改代码,将输出结果与父表和子表自动分离?

enter image description here

申请人类构建基于数据库表申请人如下:

enter image description here

2 个答案:

答案 0 :(得分:1)

我认为PropertyType应该是typeOf(T)typeOf(EntitySet<T>),具体取决于关系的类型。因此,您可以通过查看类型是否具有任何泛型参数来区分这两者,例如:

PropertyInfo[] props = typeof(Applicant).GetProperties();

var parents = (from r in props 
               where r.PropertyType.GenericTypeArguments.Count() == 0 
               select r.Name)
               .ToList().Dump();

var children = (from r in props 
                where r.PropertyType.GenericTypeArguments.Count() == 1 
                select r.Name)
               .ToList().Dump();

答案 1 :(得分:0)

在循环中,您可以检查PropertyInfo.DeclaringType属性。所以代码将变成(大致)

void Main()
{
    PropertyInfo[] props = typeof(Applicant).GetProperties();
    foreach (PropertyInfo prop in props)
    {
        if (prop.DeclaringType == typeof(Applicant)) 
        {
           // this is an Applicant property
           string name = prop.Name;
           // TODO: store wherever you need
        }
        else
        {
           // this is a parent table property
             string name = prop.Name;
           // TODO: store wherever you need
        }
    }
}
相关问题