【问题标题】:Ignore mapping properties with default value, using Automapper使用 Automapper 忽略具有默认值的映射属性
【发布时间】:2018-02-15 19:08:21
【问题描述】:

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

【问题讨论】:

    标签: mapping automapper


    【解决方案1】:

    关键点是检查源属性的类型,只有在满足这些条件时才映射(!= 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);
    }
    

    【讨论】:

      猜你喜欢
      • 2011-06-26
      • 1970-01-01
      • 2017-02-19
      • 2017-12-31
      • 2023-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多