jeudi 7 juin 2018

Map two objects using reflection c#

I'm creating a function to loop over an object and its childs.

But I'm having some issue when i try to map from the original object to the new object, here is the code:

public static bool MatchObjectField<T>(this T obj, string objectRoute, string value)
{

    try
    {
        var objectroutelist = objectRoute.Split('.');
        var objroute = objectroutelist.First();

        var childproperty = typeof(T).GetProperty(objroute);

        if (objectroutelist.Count() == 1)
        {
            if (childproperty.GetValue(obj).ToString().Trim() == value)
            {
                return true;
            }
            return false;
        }
        else
        {
            var instance = Activator.CreateInstance(childproperty.PropertyType);
            //childproperty.SetValue(obj, instance, null);
            //childproperty.SetValue(instance, obj, null);

            instance.MapValues(childproperty);

            instance.MatchObjectField(string.Join(".", objectroutelist.Skip(1)), value);
        }

    }
    catch (Exception e)
    {

        return false;
    }
    return false;
}

And here the class where I do the map and contains the issue.

public static void MapValues<T>(this T destination, PropertyInfo orgproperty)
{


    var orgvalues = orgproperty.GetPropertiesWithValues();

    var instance = Activator.CreateInstance(typeof(T));
    foreach (var property in (typeof(T)).GetProperties())
    {
        try
        {
            var value = orgvalues.FirstOrDefault(a => a.Key == property.Name);
            property.SetValue(instance, value);
        }
        catch (Exception)
        {
            property.SetValue(instance, null);
        }
    }
    destination = (T)(object)instance;
}

The idea of the function is call with objectName.MatchObjectField("parent.child.child.child","MyName")

When I try to compare a field in the parent like objectName.MatchObjectField("Country","Ireland") it works perfectly

But when I try to create the child structure doing a call like objectName.MatchObjectField("Country.Address.City","Dublin") it breaks when I try to map to the new object.

What I noticed is that the property destination into the method MapValues<T> is mapped as Country.Address with all the properties as null which is correct. But (typeof(T)).GetProperties() doesn't return anything. Also i noticed that Activator.CreateInstance(typeof(T)) retunrs type {object} instead of return Country.Address that may be the reason why is not working.

Any idea how to fix this?





Aucun commentaire:

Enregistrer un commentaire