Automapper - 将多对多关联映射到平面对象的最佳实践 [英] Automapper - Bestpractice of mapping a many-to-many association into a flat object

查看:43
本文介绍了Automapper - 将多对多关联映射到平面对象的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个实体:EmployeeTeam.

I have two entities: Employee and Team.

我想要的是一个 EmployeeForm,它具有 TeamName.

What I want is an EmployeeForm that has the Name of the Team.

如何使用 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.

我想要的是一个通用方法,我可以在其中传递一个实体,选择集合并说明集合是否为 null 返回默认值或通过 lambda 表达式选择集合的属性.

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.

推荐答案

我重新思考了我的整个设计,开始改变领域模型:

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.

有了这个更简单的域模型,我可以使用AutoMapper轻松地将其映射到平面 DTO.

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>();
    }
}

是的,仅此而已:)

这是平面视图模型对象.

Here is the flat view model object.

这篇关于Automapper - 将多对多关联映射到平面对象的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆