Map only changed properties?

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


For Automapper version < 6.0

Yes; I wrote this extension method to map only dirty values from a model to Entity Framework.

public static IMappingExpression<TSource, TDestination> MapOnlyIfDirty<TSource, TDestination>(
    this IMappingExpression<TSource, TDestination> map)
{
    map.ForAllMembers(source =>
    {
        source.Condition(resolutionContext =>
        {
            if (resolutionContext.SourceValue == null)
                return !(resolutionContext.DestinationValue == null);
            return !resolutionContext.SourceValue.Equals(resolutionContext.DestinationValue);
        });
    });
    return map;
}

Example:

Mapper.CreateMap<Model, Domain>().MapOnlyIfDirty();

Tags:

C#

Automapper