将LLBLGen实体映射到DTO
本文关键字:DTO 映射 实体 LLBLGen | 更新日期: 2023-09-27 18:28:25
我正在尝试使用AutoMapper创建LLBLGen实体和DTO之间的映射。
我的DTO外观如下:
// Parent
public int Id { get; set; }
public List<Child> Children{ get; set; } // One to Many
// Child
public int Id { get; set; }
public int Parent { get; set; } // Foreign key to parent Id
ParentEntity包含一个与DTO列表同名的ChildCollection和一个Id(以及需要忽略的其他LLBL字段)。因此,当ParentEntity被映射到Parent DTO时,它也应该将ChildCollection映射到一个Children列表。
这就是我目前所得到的:
ParentEntity parentEntity = new ParentEntity(id);
AutoMapper.Mapper.CreateMap<ParentEntity, Parent>();
AutoMapper.Mapper.CreateMap<ChildCollection, List<Child>>();
var parent = AutoMapper.Mapper.Map<Parent>(parentEntity);
这导致Id被映射,但列表的计数为0。
我怎样才能让它工作?
更新:
尝试了与我之前的尝试相同的操作,但手动映射子项列表也会导致相同的问题:Id被映射,但列表为空。
Mapper.CreateMap<ParentEntity, Parent>()
.ForMember(dto => dto.Children, opt => opt.MapFrom(m => m.Children));
这一行没有帮助:
AutoMapper.Mapper.CreateMap<ChildCollection, List<Child>>();
相反,您应该将显式映射类添加到类中:
AutoMapper.Mapper.CreateMap<ChildEntity, Child>();
然后您应该指定要映射的确切属性。两个属性都应具有List类型或类似类型(List<ChildEntity>
作为源,List<Child>
作为目标)。因此,如果ParentEntity
和Parent
类都具有Children
属性,则甚至不必指定:
.ForMember(dto => dto.Children, opt => opt.MapFrom(m => m.Children));
足够的默认映射:
Mapper.CreateMap<ParentEntity, Parent>();