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.
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.
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.
精彩评论