开发者

AutoMapper limit depth of mapping or map lazily

AutoMapper is great, saves a lot of time, but when I started looking at the performance of my application AutoMapper is responsible for performance loss.

I'm using lazy loading with NHibernate. Most of the time a need parent entity without needing to access child entities at all. In reality what happens is that AutoMapper tries to map as many relationships as possible causing NHibernate to lazy load all the child entities (I'm seeing SELECT N+1 happening all the time).

Is there way to limit how deep AutoMapper goes or is it possible for AutoMapper to map child entities lazily开发者_如何转开发?


You could use the ignore method for associations you don't need to have loaded.

Mapper.CreateMap<User, UserDto>()
    .ForMember(dest => dest.LazyCollection, opt => opt.Ignore())
    .ForMember(dest => dest.AnotherLazyCollection, opt => opt.Ignore())
Mapper.CreateMap<UserProperty, UserPropertyDto>()
    .ForMember(dest => dest.PropertyLazyReference, opt => opt.Ignore());
return Mapper.Map<User, UserDto>(user);

For associations you know you will need in your dto, you should look at ways of fetching these more efficiently with the initial query, but that is a whole new problem.


Perhaps you should consider using two different dtos; one that includes the child entities, and one that doesn't. You can then return the proper dto from your service layer depending upon the context.


I'm using pre conditions to prevent data from being mapped.

CreateMap<Team, TeamDto>()
    .ForMember(dto => dto.Users, options =>
    {
        options.PreCondition(ctx => !ctx.Items.ContainsKey(AutoMapperItemKeys.SKIP_TEAM_USERS));
        options.MapFrom(t => t.TeamUsers.Where(tu => tu.IsDeleted == false));
    })
    .ReverseMap();

When Map() is called I feed the Items dictionary with skip keys for the properties I don't want mapped.

this.mapper.Map<IEnumerable<Team>, IEnumerable<TeamDto>>(teams, opts =>
{
    opts.Items.Add(AutoMapperItemKeys.SKIP_TEAM_USERS, true);
});

Advantages:

  • you can fine-grain which properties not to map
  • prevents from mapping to deep with nested objects
  • no need for duplicate dto's
  • no duplicate mapping profiles
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜