地图只更改了属性?

Sam*_*Sam 11 c# automapper

使用AutoMapper,是否可以仅将已更改的属性从视图模型映射到域对象?

我遇到的问题是,如果视图模型上有未更改的属性(null),那么它们将覆盖域对象并持久保存到数据库.

CGK*_*CGK 14

是的,可以完成,但您必须Condition()在映射配置中指定何时跳过目标属性.

这是一个例子.考虑以下类:

public class Source
{
    public string Text { get; set; }
    public bool Map { get; set; }
}

public class Destination
{
    public string Text { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

第一张地图不会覆盖destination.Text,但第二张会覆盖.

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);
Run Code Online (Sandbox Code Playgroud)


Bei*_*ZHU 6

@Matthew Steven Monkan 是正确的,但 AutoMapper 似乎更改了 API。我将发布新的供其他人参考。

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;
    }
Run Code Online (Sandbox Code Playgroud)

就这样