mardi 24 novembre 2015

Getting and setting the value of nested properties

I have these classes

 public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public virtual Address Address { get; set; }
    }

    public class Address
    {
        public string Line1 { get; set; }
        public string Line2 { get; set; }
    }

 public class Flat
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public virtual Address Address { get; set; }
    }

This is the code I am using to set the values on Flat class

var employee = new Employee() { ID = 1, Name = "Test",  Address = new Address() {Line1 = "1", Line2 = "2" } };
            Flat flat = new Flat();

            Map(employee, flat);

static void Map<TI, VI>(TI source, VI result)
        {
            foreach (PropertyInfo item source.GetType().GetRuntimeProperties())
            {
              if (item.GetValue(source) != null)
                {
                  if (result.GetType().GetRuntimeProperty(item.Name) != null)
                        {
                            Type type = result.GetType().GetRuntimeProperty(item.Name).PropertyType;

                            var innerObj = FormatterServices.GetUninitializedObject(type);
                            result.GetType().GetRuntimeProperty(item.Name).SetValue(result, innerObj);
                            Map(item.GetValue(source), innerObj);
                        }
                        else
                        {
                            Map(item.GetValue(source), result);
                        }
                }   
            }              
        }
    }

I would really appreciate if you could advise me if this is the right approach to map the nested properties. If this is not the case please provide alternatives.





Aucun commentaire:

Enregistrer un commentaire