开发者

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

I have two entities: Employee and Team.

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

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

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

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.


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

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

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.

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜