Automapper将DTO展平给带有孩子集合的父级 [英] Automapper flattened DTO to Parent with Child Collection
问题描述
我有一个扁平化的DTO,需要将其映射到有孩子的父母"关系.我想通过AutoMapper进行此操作,因为我正在其他地方使用它,并且效果很好.我已经看到了映射父级和子级的示例,但当子级"是一个集合并且源是扁平化的DTO时,则没有.我创建了一些类,可用于正确配置.下面是我的示例类:
I have a flattened DTO which I need to map to a Parent with Children relationship. I'd like to do this via AutoMapper as I'm using it in other places and it works great. I've seen examples of mapping a Parent and Child but not when the Child is a collection and the source is a flattened DTO. I've created some classes that I can use for getting the configuration correct. Below are my sample classes:
public class Parent
{
public int ParentId { get; set; }
public string ParentName { get; set; }
public List<Child> Children { get; set; }
}
public class Child
{
public int ChildId { get; set; }
public string ChildName { get; set; }
}
public class ParentChildDTO
{
public int ParentId { get; set; }
public string ParentName { get; set; }
public int ChildId { get; set; }
public string ChildName { get; set; }
}
我正在启动时执行映射器初始化.在尝试执行映射之前,我不会收到任何错误.下面是我的映射器初始化代码.我一直留在注释行中,以显示我尝试完成此操作的另一种方式:
I'm performing the mapper initialization on startup. I'm not getting any errors until I try to perform the mapping. Below is my mapper initialization code. I've kept in the commented out line to show the other way that I've tried to accomplish this:
AutoMapper.Mapper.Initialize(cfg =>
{
cfg.CreateMap<ParentChildDTO, Child>();
cfg.CreateMap<ParentChildDTO, Parent>()
.ForMember(dest => dest.Children, opt => opt.MapFrom(src => src));
//.ForMember(dest => dest.Children, opt => opt.MapFrom(src => new Child { ChildId = src.ChildId, ChildName = src.ChildName }));
});
以下是我用于尝试执行映射配置的代码:
Below is my code that I'm using for trying to perform the mapping configuration:
ParentChildDTO parentChildDTO = new ParentChildDTO { ParentId = 1, ParentName = "Parent Name", ChildId = 2, ChildName = "Child Name" };
Parent parent = AutoMapper.Mapper.Map<ParentChildDTO, Parent>(parentChildDTO);
List<LienActivity> mapTest = AutoMapper.Mapper.Map<List<BaseActivityUploadDTO>, List<LienActivity>>(request.Activities);
我曾考虑使用自定义值解析器,但希望通过正确的配置可以避免复杂性和额外的代码.
I've considered using a Custom Value Resolver, but was hoping to avoid the complexity and extra code if what I'm doing is possible with the correct configuration.
这是上面代码的错误:
错误映射类型.
Error mapping types.
映射类型:ParentChildDTO->父
Mapping types: ParentChildDTO -> Parent
类型映射配置:ParentChildDTO->父
Type Map configuration: ParentChildDTO -> Parent
财产:儿童
推荐答案
这里是您仅为Children属性定义自定义映射的另一个选项.
Here is another option where you define custom mapping just for the Children property.
Mapper.Initialize(cfg =>
{
cfg.CreateMap<ParentChildDTO, Parent>()
.ForMember(d => d.Children,
opt => opt.MapFrom(src => new List<Child>() { new Child() { ChildId = src.ChildId, ChildName = src.ChildName } }));
});
这篇关于Automapper将DTO展平给带有孩子集合的父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!