使用 Automapper 忽略具有默认值的映射属性

Ignore mapping properties with default value, using Automapper

我使用 Automapper 将对象 source 映射到对象 destination。 有什么方法可以只映射具有非默认值的属性,从 source 对象到 destination 对象?

关键是检查源属性的类型,只有满足这些条件才映射(!= null为引用类型,!= default为值类型) :

Mapper.CreateMap<Src, Dest>()
    .ForAllMembers(opt => opt.Condition(
        context => (context.SourceType.IsClass && !context.IsSourceValueNull)
            || ( context.SourceType.IsValueType
                 && !context.SourceValue.Equals(Activator.CreateInstance(context.SourceType))
                )));

完整的解决方案是:

public class Src
{
    public int V1 { get; set; }
    public int V2 { get; set; }
    public CustomClass R1 { get; set; }
    public CustomClass R2 { get; set; }
}

public class Dest
{
    public int V1 { get; set; }
    public int V2 { get; set; }
    public CustomClass R1 { get; set; }
    public CustomClass R2 { get; set; }
}

public class CustomClass
{
    public CustomClass(string id) { Id = id; }

    public string Id { get; set; }
}

[Test]
public void IgnorePropertiesWithDefaultValue_Test()
{
    Mapper.CreateMap<Src, Dest>()
        .ForAllMembers(opt => opt.Condition(
            context => (context.SourceType.IsClass && !context.IsSourceValueNull)
                || ( context.SourceType.IsValueType
                     && !context.SourceValue.Equals(Activator.CreateInstance(context.SourceType))
                    )));

    var src = new Src();
    src.V2 = 42;
    src.R2 = new CustomClass("src obj");

    var dest = new Dest();
    dest.V1 = 1;
    dest.R1 = new CustomClass("dest obj");

    Mapper.Map(src, dest);

    //not mapped because of null/default value in src
    Assert.AreEqual(1, dest.V1);
    Assert.AreEqual("dest obj", dest.R1.Id);

    //mapped 
    Assert.AreEqual(42, dest.V2);
    Assert.AreEqual("src obj", dest.R2.Id);
}