Using AutoMapper, is it possible to map only the changed properties from the View Model to the Domain Object?
The problem I am coming across is that if there are properties on the View Model that are not changed (null), then they are overwriting the Domain Objects and getting persisted to the database.
Yes, it can be done, but you have to specify when to skip the destination property using Condition()
in your mapping configuration.
Here's an example. Consider the following classes:
public class Source
{
public string Text { get; set; }
public bool Map { get; set; }
}
public class Destination
{
public string Text { get; set; }
}
The first map won't overwrite destination.Text
, but the second will.
Mapper.CreateMap<Source, Destination>()
.ForMember(dest => dest.Text, opt => opt.Condition(src => src.Map));
var source = new Source { Text = "Do not map", Map = false };
var destination = new Destination { Text = "Leave me alone" };
Mapper.Map(source, destination);
source.Map = true;
var destination2 = new Destination { Text = "I'll be overwritten" };
Mapper.Map(source, destination2);
@Matthew Steven Monkan is correct, but seems AutoMapper changed API. I will put new one for others refer.
public static IMappingExpression<TSource, TDestination> MapOnlyIfChanged<TSource, TDestination>(this IMappingExpression<TSource, TDestination> map)
{
map.ForAllMembers(source =>
{
source.Condition((sourceObject, destObject, sourceProperty, destProperty) =>
{
if (sourceProperty == null)
return !(destProperty == null);
return !sourceProperty.Equals(destProperty);
});
});
return map;
}
that's all
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With