Using AutoMapper to merge objects

前端 未结 2 469
时光取名叫无心
时光取名叫无心 2020-12-19 11:50

I\'m attempting to use AutoMapper to merge data from multiple objects, and I\'m running into a couple issues that I can\'t seem to solve.

I have an object like:

相关标签:
2条回答
  • 2020-12-19 11:58

    Automapper is capable of this, your mapper needs to be configured as such:

    Mapper.Initialize(cfg =>
    {
        // necessary if you are mapping parent to a parent
        cfg.CreateMap<Parent, Parent>()
            .ForAllMembers(options =>
            {
                options.Condition(src => src.DestinationValue == null);
            });
        // necessary if you are mapping your child to a child
        cfg.CreateMap<Child, Child>()
            .ForAllMembers(options =>
            {
                options.Condition(src => src.DestinationValue == null);
            });
    });
    

    And then your usage as such:

    var bigParent = new Parent
    {
        Id = "14",
        Children = new List<Child>
        {
            new Child
            {
                Key = "A",
                Value1 = 10,
                Value2 = 20,
                Value3 = 30,
                Value4 = 40,
                Value5 = 50
            }
        }
    };
    
    var merge = new Parent
    {
        Id = "14",
        Children = new List<Child>
        {
            new Child
            {
                Key = "A",
                Value1 = null,
                Value2 = null,
                Value3 = 100,
                Value4 = null,
                Value5 = null
            }
        }
    };
    
    var bigChild = new Child
    {
        Key = "A",
        Value1 = 10,
        Value2 = 20,
        Value3 = 30,
        Value4 = 40,
        Value5 = 50
    };
    
    var mergeChild = new Child
    {
        Key = "A",
        Value1 = null,
        Value2 = null,
        Value3 = 100,
        Value4 = null,
        Value5 = null
    };
    
    Mapper.Map(bigChild, mergeChild);
    Debug.Assert(mergeChild.Value3 == 100);
    
    Mapper.Map(bigParent, merge);
    Debug.Assert(merge.Children[0].Value3 == 100);
    
    0 讨论(0)
  • 2020-12-19 12:14

    If you want to ignore null values in mappings defined in AutoMapper Profile, use:

    public class MappingProfile : AutoMapper.Profile
    {
      public MappingProfile()
      {
         this.CreateMap<Parent, Parent>()
             .ForAllMembers(o => o.Condition((source, destination, member) => member != null));
      }
    }
    
    0 讨论(0)
提交回复
热议问题