Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map only changed properties?

Tags:

c#

automapper

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.

like image 285
Sam Avatar asked Apr 25 '11 17:04

Sam


2 Answers

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);
like image 111
CGK Avatar answered Sep 19 '22 21:09

CGK


@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

like image 41
BeiBei ZHU Avatar answered Sep 18 '22 21:09

BeiBei ZHU