0

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

jhoop2002
  • 33
  • 2
  • 8
  • Do you mean if ws.customer has fields-name,id,account,etc..-and ef.customer does not have for example id and account,you would like to insert them? – terrybozzio Jul 13 '13 at 20:56
  • I dont know if this is what your looking for but have a look at the ExpandoObject class http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject(v=vs.100).aspx – terrybozzio Jul 13 '13 at 21:11

2 Answers2

2

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);
Sergey Rybalkin
  • 3,004
  • 22
  • 26
  • 1
    An alternative to AutoMapper is [ValueInjecter](http://valueinjecter.codeplex.com). Here's a good SO question about [AutoMapper vs ValueInjecter](http://stackoverflow.com/q/4663577/9664) as well. – Metro Smurf Jul 14 '13 at 00:16
1

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

migajek
  • 8,524
  • 15
  • 77
  • 116