Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper: Merging values of items in a collection from one instance to another

I am trying to figure out how to merge two complex object instances using AutoMapper. The parent object has a property which is a collection of child objects:

public class Parent
{
    public List<Child> Children { get; set; }
}

public class Child
{
    public string A { get; set; }
    public string B { get; set; }
    public string C { get; set; }
}

I have two instances of Parent:

var parentOne = new Parent()
{
    Children = new List<Child>() { new Child() { A = "A", B = "B", C = "C" } }
};

var parentTwo = new Parent()
{
    Children = new List<Child>() { new Child() { C = "Updated value" } }
};

I would like to be able to merge values from parentOne to parentTwo, without overwriting the value of C in parentTwo. The maps I have created are as follows:

Mapper.CreateMap<Parent, Parent>()
    .ForMember(parent => parent.Children, opt => opt.UseDestinationValue());

Mapper.CreateMap<Child, Child>()
    .ForMember(child => child.C, opt => opt.Ignore());

Mapper.Map(parentOne, parentTwo);

As I understand it, AutoMapper will create new instances of complex properties unless you use the UseDestinationValue() option. However, after executing the code above, parentTwo.C equals "C" instead of "Updated value".

It looks to me like it's keeping the instance of List<Child>, but it is creating new instances of Child within the List. Unfortunately, I'm struggling to come up with a map that will keep each instance of Child as well.

Any help would be much appreciated!

like image 414
Gareth James Avatar asked Dec 17 '22 02:12

Gareth James


1 Answers

As far as I know, AutoMapper doesn't support this and I believe it's because of the complexities of supporting such a scenario.

The UseDestinationValue does indeed only work on the collection instance as you surmised -- not the collection elements. In your scenario, there is only one item in each list and (I assume) you want child list objects updated "in sync" (i.e. first element updates first element, second updates second, etc...). But what if one list as 3 and the other list has 5? What does "UseDestinationValue" mean if there is no destination value? And how do you pick which desintation object to map among the two child lists? In a database scenario (which it sounds like was the basis for the question) there would be unique ids or some kind of foreign key which would allow you to match up the child objects to know which one to map to. In this case, it's too hard (IMO) to write a generic mapping that would support UseDestinationValue on individual elements of a collection.

like image 175
PatrickSteele Avatar answered Jan 12 '23 00:01

PatrickSteele