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
解决方案
因为你有多个来源,我的解决方案是这样的方法
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;
}
推荐阅读
- haskell - 在haskell中创建具有多个条件的列表
- webpack - 如何加载在处理另一个模块时作为副作用生成的“动态生成”模块?
- html - 需要制作 3 列,我想使用 Divs 来做,但不工作
- .net - 为什么 SqlTransaction 被僵尸化了
- firebase - Firebase 实时数据库不会添加数据,但 Firebase 身份验证和 Firestore 可以完美运行
- c++ - 数组的静态声明和动态声明有什么区别
- flutter - 从rest api解析数据时出错-“尝试调用:演员
- html - 当元素在另一个元素中时,CSS位置粘性无法正常工作
- c++ - 使用包含回调的 SWIG GO 和 C++ 包装器创建共享库时出现问题
- javascript - 如何在 Chart.js 的图表中显示数据标签?