0

I have a task where I am provided a base object that contains objects and primitives from our dataservice, and couple it with data provided on an identical object that the client provides. It needs to end up being one complete object. I'll refer to the object as "MyObject".

Here is what the object looks like from the dataservice:

MyObject.FirstName = null
MyObject.LastName = null
MyObject.DataProperty1 = anotherobject
   anotherobject.property1 = somevalue1
   anotherobject.property2 = somevalue2
   anotherobject.property2 = somevalue2
MyObject.DataProperty2 = yetanotherobject
   yetanotherobject.property1 = someothervalue1
   yetanotherobject.property2 = someothervalue2
   yetanotherobject.property3 = someothervalue3
   yetanotherobject.property4 = someothervalue4

Here is what the object looks like when provided by the client side

MyObject.FirstName = John
MyObject.LastName = Doe
MyObject.DataProperty1 = anotherobject
   anotherobject.property1 = null
   anotherobject.property2 = null
   anotherobject.property2 = null
MyObject.DataProperty2 = yetanotherobject
   yetanotherobject.property1 = null
   yetanotherobject.property2 = null
   yetanotherobject.property3 = null
   yetanotherobject.property4 = null

I can't expect to know exactly which sub item objects will be null or not, but I do know that recursively, I need the final merged object to contain the actual data from both original objects, and not the nulls. Obviously the objects are going to be way more complicated that what i've typed above, but the gist is of my question is valid.

I've tried doing something like merging two objects in C# I couldn't figure out the non-primitives.

I really don't think this is a task for AutoMapper since the type of MyObject is the same class for both the client and the data side. It wouldn't make sense to map it to itself.

Too bad i cant just go MyObject1 + MyObject2 = NewCombinedObject haha.

Also, this is legacy code and I realize its not 'best practice' at all. Still need to solve the problem though.

CarComp
  • 1,929
  • 1
  • 21
  • 47

1 Answers1

0

I can see two issues you will run into with this that are potential show-stoppers: nested object references and children that refer to their parents. Both can lead to infinite recursion scenarios and out of memory errors.

You can mitigate the nesting issue by simply deciding you won't merge any deeper than, say, x levels deep. It's not ideal, but it can prevent infinite recursion for that scenario.

The issue with children referring to their parents is more complex. You have to be able to map merged objects to their originals and then, in your output, map the referring node back to the one you've already merged. This is not a task for the faint of heart.

Is this a task that AutoMapper can't do for you? If it is, my gut tells me that it will do this for you far better than you can reinvent it, and with a greatly reduced risk of errors.

Mike Hofer
  • 16,477
  • 11
  • 74
  • 110