Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get property of entity of entity by name

Tags:

c#

reflection

in class Person i have relation to class Position, and the class Position has a relation to class PositionTitle, and the PositionTitle has a property named Title

public class Person
{
  public position Position{get;set;}
  public string Name{get;set;}
  public DateTime BirthDate{get;set;}
  public bool IsAdmin{get;set;}
  public int Age{get;set;}
}

public class position  
{
  public positionTitle PositionTitle{get;set;}
  public bool IsSystem{get;set;}
}

public class PositionTitle
{
  public string Title{get;set;}
}

i have a string "Person.Position.PositionTitle.Title", how can i get this property of person with this string??

EDIT:

i should add sth, im gonna get all properties of person till getting to system types,, i mean i wanna have these propertis as string { Name,Age,IsAdmin,BirthDate,IsSystem,Title}

how could I?

EDiT2: one more problem,, Position itself can have a relation to Person, and if i get properties of person and recursively get properties of those classes that person have a relation to,, there would be a non stop loop, because Person has a Position and Position has a Person

like image 724
Adrakadabra Avatar asked Oct 26 '25 12:10

Adrakadabra


1 Answers

Basically you split the string by the '.', then loop through each substring, using reflection to get the property of the current instance. Then set the instance to the property you've just got.

You'll end up with the property you're after.

    /// <summary>
    /// Gets an object property's value, recursively traversing it's properties if needed.
    /// </summary>
    /// <param name="FrameObject">The object.</param>
    /// <param name="PropertyString">The object property string.
    /// Can be the property of a property. e.g. Position.X</param>
    /// <returns>The value of this object's property.</returns>
    private object GetObjectPropertyValue(Object FrameObject, string PropertyString)
    {
        object Result = FrameObject;

        string[] Properties = PropertyString.Split('.');

        foreach (var Property in Properties)
        {
            Result = Result.GetType().GetProperty(Property).GetValue(Result, null);
        }

        return Result;
    }

Disclamer: This works for my use, watch out for null references etc!

like image 52
George Duckett Avatar answered Oct 29 '25 00:10

George Duckett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!