Mapping readonly child collection with AutoMapper

前端 未结 2 939
野的像风
野的像风 2021-02-19 02:37

It\'s not so much a question, as I have found a way to do what I want, but it seems like there should be a better way to do it. I\'ve searched everywhere and not found anything.

相关标签:
2条回答
  • 2021-02-19 03:00

    I don't like to have logic inside property getter or setter, but what about adding setter to Children property of Parent class

    public class Parent
    {
        private readonly IList<Child> _children = new List<Child>();
    
        public IEnumerable<Child> Children
        {
            get => _children;
            set => AddChildren(value);
        }
    
        public void AddChild(Child child)
        {
            child.Parent = this;
            _children.Add(child);
        }
    
        private void AddChildren(IEnumerable<Child> children)
        {
            _children.Clear();
    
            foreach (var child in children)
            {
                AddChild(child);
            }
        }
    }
    

    And AfterMap logic is not more necessary. Mapping configuration will be simple

    Mapper.CreateMap<ParentDTO, Parent>();
    
    0 讨论(0)
  • 2021-02-19 03:13

    I think if you are going to protect properties for good business logic reasons then it would be bad if AutoMapper circumvented them when doing its mapping. In situations like this I prefer to abandon the fluent syntax and place the creation logic in its own method like this:

    private Parent MapParentDTOToParent(ParentDTO source)
    {
        var parent = new Parent();
        // Business logic here
        return parent
    }
    

    and then:

    Mapper.CreateMap<ParentDTO, Parent>().ConvertUsing(MapParentDTOToParent);
    

    I find this easier to follow than having lots of ignore declarations.

    0 讨论(0)
提交回复
热议问题