vendredi 26 juillet 2019

How to set Object's properties and its value if that Object is a property of Object that is inside of the List using Reflections

I had a similar question before, but this one will need a different solution.

I have object on my Model and object on my service.

I need to set value of Model's object property to a value of properties coming from the service's List<TicketReportPropertyEntity> if both objects' properties are the same.

This is a Model:

public class MyModel{

     public ObjectAEntity ObjectAData { get; set; }
     public ObjectBEntity ObjectBData { get; set; }
}

ObjectAEntity has a property called "SalesAmount"

This is a service:

public class MyScreenClass
{
     public List<TicketReportPropertyEntity> TicketReportPropertyEntities { get; set; } 
}

public class TicketReportPropertyEntity
{
    public decimal Amount{get;set;}
    public ReportPropertyEntity ReportProperty {get;set;}
} 

public class ReportPropertyEntity
{
    public string ReportGroup { get; set; }        
    public string PropertyName { get; set; }
}

All the properties, their values and which section(ReportGroup) on the screen they belong to (ObjectAData to the LeftSection and ObjectBData to the RightSection) I'm getting using a reflection from List<TicketReportPropertyEntity> in the following method:

private void SetValues(MyModel m, ObjectAEntity bo, object objectType)
{
    string leftSection = "LeftSection";
    string rightSection = "RightSection";


    m.ObjectAData.SaleAmount = bo.ObjectAData.SaleAmount;
    foreach (var ticketReportEntity in mol.TicketReportPropertyEntities)
    {
        var type = ticketReportEntity.GetType();
        PropertyInfo reportProperty = type.GetProperty("ReportProperty");
        PropertyInfo reportPropertyName = typeof(ReportPropertyEntity).GetProperty("PropertyName");
        PropertyInfo reportPropertyReportGroup = typeof(ReportPropertyEntity).GetProperty("ReportGroup");
        PropertyInfo amountProperty = type.GetProperty("Amount");
        ReportPropertyEntity reportPropertyValue = (ReportPropertyEntity)reportProperty.GetValue(ticketReportEntity, null);
        string reportPropertyNameValue = (string)reportPropertyName.GetValue(reportPropertyValue, null);
        decimal value = (decimal)amountProperty.GetValue(ticketReportEntity, null);


//here I need to see if Model's object has the same property as in `ReportProperty` class. 

bool has = m.TicketReportPropertyEntities.Any(element => element.ReportProperty.PropertyName.Equals(reportPropertyNameValue));

    if (has)
    {
        //need to set the value of the Model's `ObjectAEntity` property 
    }
}

How can I do something like that?





Aucun commentaire:

Enregistrer un commentaire