0

I have two domain classes

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

}
public class Address
{
    public string HouseName { get; set; }
    public string StreetName { get; set; }
    public string PinCode { get; set; }
}

I want to map object of Employee class to another class. I am using reflection to map empData object to another object. The code i used is

private void GetValues(object empData)
{
    System.Type type = empData.GetType();

    foreach (PropertyInfo pInfo in type.GetProperties())
    {
        //do some stuff using this pInfo. 
    }
}

I could easily map all the properties except the Address property in the emp object which is an object of another class. So how can i map all the properties irrespective of its type ? i.e, if address contains object of another class it should also get mapped.

j0k
  • 22,600
  • 28
  • 79
  • 90
BonDaviD
  • 961
  • 3
  • 11
  • 27

3 Answers3

1

Can't you use AutoMapper for mapping classes?

rt2800
  • 3,045
  • 2
  • 19
  • 26
0

You can know the type of property you are mapping by

if (propertyInfo.PropertyType == typeof(Address))
    { // do now get all properties of this object and map them}
Rahul
  • 31
  • 2
  • While this works, it sort of removes the point of using reflection doesn't it? This is just a one-off solution for a specific property on a specific object that we already know all (three) properties on already. – Anders Arpi Jul 26 '12 at 07:23
0

Assuming that you want to be able to do this on any type of object and not just this specific one, you should use some sort of recursive solution. However if it's just for this object - why are you even using reflection? To me it just adds unnecessary complexity to something as simple as mapping six properties to another set of objects.

If you want to get more concrete help with code examples, you'll have to give us some more context. Why does a method named "GetValues" has a return type of void? I have a hard time coding up an example with that in mind. :)

Anders Arpi
  • 8,277
  • 3
  • 33
  • 49