3

I have an object in C# with lets say 20 properties and it's 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 this other than assigning each property of one object to the corresponding properties of the other?

5 Answers 5

5

Yes, take a look at Automapper

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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

Comments

1

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.

Comments

0

C# Object Clone Wars might be a good starting point.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.