My question is similar to this question, only that I need to merge deeper levels.
I have two similar objects of the same type. I need to merge these together into a final result. One object is populated with data from a more reliable source, while the other object is more complete. My final result should contain all values from the more reliable source. But when a value is not present in the reliable source it should be filled from the more complete source.
My objects look like this (simplified):
public class Body {
int Id
Client Client
Details Details
}
public class Client {
int Id
Name Name
Address Address
}
public Name {
string FirstName
string LastName
etc...
}
public class Address {
string StreetName
string HouseNumber
etc...
}
public class Details {
Details1 Details1
Details2 Details2
many more classes which contains more nested classes...
}
So, I found that I can use the AutoMapper Condition
option to specify that only null values in the destination class should be mapped.
Mapper.CreateMap<Body, Body>()
.ForAllMembers(opt => opt.Condition(dest => dest.DestinationValue == null));
Mapper.Map(completeObject, reliableObject);
But ForAllMembers
only applies to the direct child members of that class. So the above statement will only check if the Id, Client en Details fields in reliableObject
are null. It will not check values on deeper levels in the schema, for instance reliableObject.Client.Address.StreetName
.
To achieve this I'd have to configure the Condition
option for every class in my schema, which are a lot, and map them separately.
Is there a way to tell AutoMapper to apply this Condition to every level of the schema? Is AutoMapper even the best way to merge these objects?
I'm using AutoMapper version 3.2.1.