Search code examples
c#asp.netreflectionpropertyinfo

How to return Virtual Attribute PropertyInfo?


I'm having difficulty returning the attributes of a virtual value in my entity model, does anyone know how I can return the PropertyInfo of this virtual attribute?

I have the following entities:

Entities

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; }
}

However I am not able to access the attributes of the Owner model when returning the Owner PropertyInfo in the Model Company.

Basic example:

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

   return prop;
}

The variable prop returns null

Am I forgetting to implement something?


Solution

  • You need to get Owner property first then get the Name through it:

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

    Or just get it directly if you have access to Owner:

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