views:

122

answers:

2

Hello,

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?

A: 

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.

DanP
+3  A: 

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.

Sam
I ended up using custom resolvers, thank you for your suggestion
Daniil Harik