使用自动映射器将多个列表转换为单个主子对象列表

时间:2019-09-18 09:30:11

标签: c# 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

1 个答案:

答案 0 :(得分:1)

因为您有多个来源,所以我的解决方案是类似

的方法
    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;
    }