Automapper - 一个多一对多关联映射到一个平面物体的Bestpractice [英] Automapper - Bestpractice of mapping a many-to-many association into a flat object
问题描述
我有两个实体:员工
和团队
。
我要的是一个 EmployeeForm
具有名称
的团队的code>。
我怎样才能做到这一点使用的 AutoMapper
How can I achieve this using AutoMapper?
我目前的解决方案是这样的:
My current "solution" is the following:
Mapper.CreateMap<Employee, EmployeeForm>()
.ForMember(dest => dest.TeamName, opt => opt.MapFrom(x => x.GetTeams().FirstOrDefault() != null ? string.Join(", ", x.GetTeams().Select(y=>y.Name)) : "n/a"));
在我看来,这是不好的可读性。
In my opinion this is bad readable.
我想有一个通用的方法,在那里我可以通过一个实体,选择收集和说,如果集合为空返回默认值或以其他方式通过拉姆达前pressions选择收藏的财产。
What I would like to have is a generic method where I can pass an entity, choosing the collection and saying if collection is null return a default value or otherwise choose the property of the collection via lambda expressions.
推荐答案
我rethinked我的整个设计开始改变在域模型
I rethinked my whole design starting to change the domain model:
我改变了许多-to-many关联使用的是关系表
成两一to-many关联
通过这更容易的域模型,我可以轻松地这个映射到一个平DTO 使用的 AutoMapper
With this more easier domain model, I can easily map this into a flat DTO using AutoMapper.
public class TeamEmployeeMapperProfile : Profile
{
protected override void Configure()
{
CreateMap<TeamEmployee, TeamEmployeeForm>();
}
}
是的,这是所有:)
Yes that's all :)
下面是平面视图模型对象。
Here is the flat view model object.
这篇关于Automapper - 一个多一对多关联映射到一个平面物体的Bestpractice的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!