views:

23

answers:

1

Hey all,

My question might be silly, but I'm pretty sure I miss a very important part of the issue. I have to do some object to object mapping (between domain classes used in C# project and classes which are sent to flash clients).

My first choice was Automapper. But Ive had some issues with it (nested properties, not paramterless constructor defined). It turns out that it is not so easy to map a really complex type with automapper.

Then my question is: Why not implement methods like:

  ClassA GetClassAByClassB(ClassB pObj)

   {  
     ClassA objA = new ClassA();  
     objA.Prop1 = pObj.Prop1;  
     objA.NestedType.Prop2 = pObj.Prop2;  
     //....Some more.....  
     return objA;  
   }  

It has exactly the same level of flexibility like mapping done using Automapper. You still have to provide which property from source object are copied into what properties in destinations object. You just do this using '=' and not lambda expression.

But if you change something in your domain classes you have to change this "mapping" part anyway. So what is the main thing which should convince me to using Automapper (as I said at the beginning I'm pretty sure I'm missing something important).

A: 

Because with AutoMapper you don't have to implement those methods ;-)

Your approach requires writing a lot of

classA.propA = classB.propA;
classA.propB = classB.propB;
classA.propC = classB.propC;
classA.propD = classB.propD;
classA.propE = classB.propE;

AutoMapper uses conventions to figure it itself. What is more, you don't have to worry about pObj == null (your code will throw NulLReferenceException in this case).

You can also define conversions in your map (ie. string to DateTime).

Mapper.CreateMap<User, UserModel>().ForMember(d => d.LastLogin, c => c.MapFrom<DateTime?>(u => u.Credential.LastLogin));

AutoMapper supports nested properties as well.

Read more here: AutoMapper Introduction and Samples

Jakub Konecki
What about properties which dont have the same names? And nested Properties? I think I should change conventions, but sometimes property on one side is 'PositionX' and on he other side just 'X'. (just an example - the properties anmes might be quite unpredictable). So isnt it like I should not use Automapper in my case?
Katalonis
@Katalonis - Then you configure the mapper in the type-safe manner using lambdas. Added a code sample and link.
Jakub Konecki

related questions