tags:

views:

133

answers:

5

hi, I have an object in C# with lets say 20 properties and its a part of a datacontract. I also have another business entity with similar properties, which i want to populate from the response object. is there any way to do it other than assigning each properties of one object to corresponding properties of the other.

thanks

+4  A: 

Yes, take a look at Automapper

Igor Brejc
A: 

This might be a good starting point.

Hooray Im Helping
A: 

Reflection is an option if you want to do it in an automated manner, provided the property names are easily mappable between the objects.

Chad Ruppert
A: 

Automapper is worth a try, but in the end, I decided it wasn't for me. The big problem with those sorts of tools is you incur a great deal of runtime overhead each and every time a mapping occurs. I asked this same question last week and I ended up rolling my own solution (look at the accepted answer). You're free to modify the source I provided, I make no claims as to it's effectiveness, suitability, performance, you-break-it-you-get-to-keep-the-pieces, etc., but it works well enough for me to create design time object to object mapping.

Wayne Hartman
+1  A: 

MiscUtil has an answer to this (PropertyCopy) that uses Expression (.NET 3.5) and a static field to cache the compiled delegate (so there is negligible cost per invoke):

DestType clone = PropertyCopy<DestType>.CopyFrom(original);

If you are using 2.0, then probably reflection would be your friend. You can use HyperDescriptor to improve the performance if you need.

Marc Gravell