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)
@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)
就这样