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

时间:2016-05-12 18:25:41

标签: mapping automapper

我使用Automapper将对象source映射到对象destination。 有没有办法映射,只有具有非默认值的属性,从source对象到destination对象?

1 个答案:

答案 0 :(得分:4)

关键是检查源属性的类型并仅在满足这些条件时进行映射(对于引用类型为!= 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);
}
相关问题