jhoop2002
jhoop2002

Reputation: 43

Merging Objects of different types

I have two objects (WS.Customer and EF.Customer). The reason for this is my vendor didn't expose all of the fields in their object (WS.Customer) and I need to insert and update into those fields.

I need to merge WS.Customer -> EF.Customer and later merge EF.Customer -> WS.Customer. EF.Customer will have some extra fields that WS.Customer won't have, but when the field names match - I want the values merged.

I also only want to merge values where the destination field is null, empty, or a default value in case of a Guid.

I know I could use to Linq to query each object and build the other, but is there a less verbose way of doing things? I have some other objects I need to use this approach for and don't feel like spending a weeks typing away.

Thanks

Upvotes: 0

Views: 138

Answers (2)

Sergey Rybalkin
Sergey Rybalkin

Reputation: 3026

You can use one of the available object-to-object mappers library like AutoMapper or EmitMapper. They will take care of copying the data in both directions and skip fields if properly configured. For example with EmitMapper your code might look like this:

ObjectMapperManager.DefaultInstance
                   .GetMapper<WS.Customer, EF.Customer>(<your configuration object here>)
                   .Map(customerSource, customerDestination);

Upvotes: 2

migajek
migajek

Reputation: 8614

What do you mean by "merged"? I guess you need to "translate" from one instance to another, i.e. copy values when name and type of property matches. Please have a look at the implementation provided in ServiceStack, the extension method of object - TranslateTo method: https://github.com/ServiceStack/ServiceStack/blob/master/src/ServiceStack.Common/ReflectionExtensions.cs#L31

Upvotes: 1

Related Questions