I'd ideally like to use AutoMapper to apply updates to a complex type that contains several of its own lists of complex types. I know this is trivially done as AutoMapper will handle mapping on properties within the base type.
However, because I'm looking to update this (based on a PUT request), each of the objects has an ID. Ideally, then, this means that I'm not just creating new objects so much as mapping into an existing object and its properties. Now, for the root this is easy enough, because my mappings look like:
CreateMap<MyObj,MyObj>
.ForMember(dest => dest.Id, opt => opt.Ignore());
CreateMap<MyOtherObj, MyOtherObj>
.ForMember(dest => dest.Id, opt => opt.Ignore());
However, let's say that MyObj looks like the following:
public class MyObj
{
public int Id {get;set;}
public List<MyOtherObj> Objs {get;set;}
}
And MyOtherObj looks like:
public class MyOtherObj
{
public int Id {get;set;}
public string Name {get;set;}
}
I'm starting with the following:
var originalObj = new MyObj
{
Id = 1,
Objs = new List<MyOtherObj>
{
new MyOtherObj
{
Id = 1,
Name = "Apple"
},
new MyOtherObj
{
Id = 2,
Name = "Banana"
}
}
};
Then I receive the following in a PUT request:
var updateObj = new MyObj
{
Id = 1,
Objs = new List<MyOtherObj>
{
new MyOtherObj
{
Id = 2,
Name = "Cherry"
},
new MyOtherObj
{
Id = 1,
Name = "Date"
}
}
};
I'd like to be able to just do something like:
var mappedObj = _mapper.Map(updateObj, originalObj);
The issue though is that I can't figure out how to inform AutoMapper about the identifier so instead of blindly mapping through the Objs, it actually matches the list up by ID (between the original and updated versions) and then applies the mapping.
Questions:
- Is such a thing possible?
- If so, can it be taken further with a .When() method or similar so I can a) map updates for matching IDs, b) create new objects where my update contains IDs not in the original, and c) remove those objects from the original that aren't in the update (again, by ID and so I don't have to manually deal with each of the properties in my base object)?
Thank you!