I\'m attempting to use AutoMapper to merge data from multiple objects, and I\'m running into a couple issues that I can\'t seem to solve.
I have an object like:
Automapper is capable of this, your mapper needs to be configured as such:
Mapper.Initialize(cfg =>
{
// necessary if you are mapping parent to a parent
cfg.CreateMap<Parent, Parent>()
.ForAllMembers(options =>
{
options.Condition(src => src.DestinationValue == null);
});
// necessary if you are mapping your child to a child
cfg.CreateMap<Child, Child>()
.ForAllMembers(options =>
{
options.Condition(src => src.DestinationValue == null);
});
});
And then your usage as such:
var bigParent = new Parent
{
Id = "14",
Children = new List<Child>
{
new Child
{
Key = "A",
Value1 = 10,
Value2 = 20,
Value3 = 30,
Value4 = 40,
Value5 = 50
}
}
};
var merge = new Parent
{
Id = "14",
Children = new List<Child>
{
new Child
{
Key = "A",
Value1 = null,
Value2 = null,
Value3 = 100,
Value4 = null,
Value5 = null
}
}
};
var bigChild = new Child
{
Key = "A",
Value1 = 10,
Value2 = 20,
Value3 = 30,
Value4 = 40,
Value5 = 50
};
var mergeChild = new Child
{
Key = "A",
Value1 = null,
Value2 = null,
Value3 = 100,
Value4 = null,
Value5 = null
};
Mapper.Map(bigChild, mergeChild);
Debug.Assert(mergeChild.Value3 == 100);
Mapper.Map(bigParent, merge);
Debug.Assert(merge.Children[0].Value3 == 100);
If you want to ignore null values in mappings defined in AutoMapper Profile, use:
public class MappingProfile : AutoMapper.Profile
{
public MappingProfile()
{
this.CreateMap<Parent, Parent>()
.ForAllMembers(o => o.Condition((source, destination, member) => member != null));
}
}