首页 > 解决方案 > 使用 Automapper 将多个列表转换为单个主子对象列表

问题描述

我有 2 个对象需要使用自动映射器转换为 Dto 对象。这两个对象是

    public class Parent
    {
        public int ParentID { get; set;}
        public string ParentCode { get; set; }
    }

    public class Child
    {
        public int ChildID { get; set; }
        public int ParentID { get; set;}
        public string ChildCode { get; set; }
    }

和 2 个 Dto 对象

    public class ParentDto
    {
        public int ParentID { get; set; }
        public string ParentCode { get; set; }
        public List<ChildDTO> ListChild { get; set; }
    }

    public class ChildDto
    {
        public int ChildID { get; set; }
        public string ChildCode { get; set; }
    }

需要转换 2 组列表

List<Parent> ListParent
List<Child> ListChild

List<ParentDto> ListParentDto

标签: c#automapper

解决方案


因为你有多个来源,我的解决方案是这样的方法

    public static List<ParentDto> MapToDto(List<Parent> parents, List<Child> childs)
    {
        List<ParentDto> parentDtos = new List<ParentDto>();
        var config = new MapperConfiguration(cfg => {

            cfg.CreateMap<Parent, ParentDto>().BeforeMap((s, d) =>
            {
                d.ListChild = new List<ChildDto>();
                foreach (var child in childs.Where(c => c.ParentID == s.ParentID))
                {
                    d.ListChild.Add(new ChildDto { ChildCode = child.ChildCode, ChildID = child.ChildID });
                }
            }).ForMember(dest => dest.ParentID, opt => opt.MapFrom(src => src.ParentID)).ForMember(dest => dest.ParentCode, opt => opt.MapFrom(src => src.ParentCode));
        });

        IMapper mapper = config.CreateMapper();

        foreach (var p in parents)
        {
            var source = p;
            var destination = mapper.Map<Parent, ParentDto>(source);
            parentDtos.Add(destination);
        }

        return parentDtos;
    }

推荐阅读