如何返回虚拟属性PropertyInfo?

时间:2018-08-01 18:03:50

标签: c# asp.net reflection propertyinfo

我在实体模型中返回虚拟值的属性时遇到困难,有人知道如何返回该虚拟属性的PropertyInfo吗?

我有以下实体:

实体

public class Company 
{
   public int Id { get; set; }
   public string Name { get; set; }
   public virtual Owner Owner { get; set; }
}

public class Owner
{
   public int Id { get; set; }
   public string Name { get; set; }
   public string Email { get; set; }
}

但是,当返回模型公司中的所有者PropertyInfo时,我无法访问所有者模型的属性。

基本示例:

public PropertyInfo GetPropertyInfo()
{
   Type tType = typeof(Company);
   PropertyInfo prop = tType.GetProperty("Owner.Name");

   return prop;
}
  

变量 prop 返回

我忘了实施一些东西吗?

1 个答案:

答案 0 :(得分:3)

您需要先获取Owner属性,然后再通过它获取Name

var owner = tType.GetProperty("Owner");

var name = owner.PropertyType.GetProperty("Name");

或者如果您有权访问Owner,就直接获得它:

var name = typeof(Owner).GetProperty("Name");