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

早过忘川 提交于 2019-12-18 17:04:12

问题


I have two entities: Employee and Team.

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

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.


回答1:


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.

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.




回答2:


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.



来源:https://stackoverflow.com/questions/3694632/automapper-bestpractice-of-mapping-a-many-to-many-association-into-a-flat-obje

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!