简体   繁体   English

Automapper - 将多对多关联映射到平面对象的最佳实践

[英]Automapper - Bestpractice of mapping a many-to-many association into a flat object

I have two entities: Employee and Team . 我有两个实体: EmployeeTeam

替代文字

What I want is an EmployeeForm that has the Name of the Team . 我想要的是一个拥有Team NameEmployeeForm

替代文字

How can I achieve this using AutoMapper ? 如何使用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. 在我看来,这是可读的。

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. 我想要的是一个通用方法,我可以传递一个实体,选择集合并说集合是否为null返回默认值,或者通过lambda表达式选择集合的属性。

I rethinked my whole design starting to change the domain model : 我重新考虑我的整个设计开始更改域模型

替代文字

I changed the many-to-many association into two one-to-many associations using a relation table. 我改变了many-to-many association成两个one-to-many associations使用关系表。

With this more easier domain model , I can easily map this into a flat DTO using AutoMapper . 使用这个更简单的域模型 ,我可以使用AutoMapper轻松将其映射到平面DTO

public class TeamEmployeeMapperProfile : Profile
{
    protected override void Configure()
    {
        CreateMap<TeamEmployee, TeamEmployeeForm>();
    }
}

Yes that's all :) 是的,这就是:)

Here is the flat view model object. 这是平面视图模型对象。

替代文字

You could create a read-only string property on Employee called "TeamNames". 您可以在Employee上创建一个名为“TeamNames”的只读字符串属性。 Put the list-building logic in there. 将列表构建逻辑放在那里。 That way, you've got a property that is testable (vs. the lambda expression) and it will make your mapping easier. 这样,你就拥有了一个可测试的属性(与lambda表达式相比),它将使你的映射更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM