Automapper - Bestpractice of mapping a many-to-man

2020-02-29 00:53发布

I have two entities: Employee and Team.

alt text

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

alt text

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.

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.

2条回答
Ridiculous、
2楼-- · 2020-02-29 01:29

You could create a read-only string property on Employee called "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.

查看更多
该账号已被封号
3楼-- · 2020-02-29 01:46

I rethinked my whole design starting to change the domain model:

alt text

I changed the many-to-many association into two one-to-many associations using a relation table.

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.

alt text

查看更多
登录 后发表回答