mercredi 20 octobre 2021

C# - Converting list of property paths along with their values into Class object dynamically

For demonstrating my problem, let's consider there are 3 entities:

    public class Employee
    {
        public string Name { get; set; }
        public Department Department { get; set; }
        public Address Address { get; set; }
    }
    public class Department
    {
        public string Id { get; set; }

        public string Name { get; set; }
    }
    public class Address
    {
        public string City { get; set; }

        public string State { get; set; }

        public string ZipCode { get; set; }
    }

And there are list of property paths along with their values:

[{
    { "Deparment.Name", "IT" },
    { "Address.City", "SomeCity" }
}]

Finally I would like to generate the employee object using these list of key value pairs. To demonstrate my problem, I've used a very simple "Employee" entity here. However, I need to convert 100s of such key value pairs into one complex object & so I'm not considering option to mapping each property manually.

Provided all the properties in this complex entity are string properties. How can we achieve this dynamically.

I've tried to solve it by looping each property path & setting the property value dynamically in below manner using c# reflection :

(Inspired from https://stackoverflow.com/a/12294308/8588207)

private void SetProperty(string compoundProperty, object target, object value)
        {
            string[] bits = compoundProperty.Split('.');
            PropertyInfo propertyToSet = null;
            Type objectType = null;
            object tempObject = null;
            for (int i = 0; i < bits.Length - 1; i++)
            {
                if (tempObject == null)
                    tempObject = target;

                propertyToSet = tempObject.GetType().GetProperty(bits[i]);
                objectType = propertyToSet.PropertyType;
                tempObject = propertyToSet.GetValue(tempObject, null);
                if (tempObject == null && objectType != null)
                {
                    tempObject = Activator.CreateInstance(objectType);
                }
            }
            propertyToSet = tempObject.GetType().GetProperty(bits.Last());
            if (propertyToSet != null && propertyToSet.CanWrite)
                propertyToSet.SetValue(target, value, null);
        }




Aucun commentaire:

Enregistrer un commentaire