使用 Automapper 将多个列表转换为单个主子对象列表
Convert Multiple List to Single Master Child object List Using Automapper
我有 2 个对象需要使用自动映射器转换为 Dto 对象。
这 2 个对象是
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
因为你有多个来源,我的解决方案是
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;
}
我有 2 个对象需要使用自动映射器转换为 Dto 对象。 这 2 个对象是
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
因为你有多个来源,我的解决方案是
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;
}