Rookian
Rookian

Reputation: 20559

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

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.

Upvotes: 5

Views: 2309

Answers (2)

Rookian
Rookian

Reputation: 20559

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

Upvotes: 2

PatrickSteele
PatrickSteele

Reputation: 14687

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.

Upvotes: 1

Related Questions