Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is automapper preventing lazy loading with EF?

I have been using an AutoMapper and it seems that it gets me all the child entities (even if I don't specify them in "Include()" clause). Is there any way how to make lazy loading possible and get child properties only if I specify them.

Thank you,

Jakub

like image 938
Jakub Holovsky Avatar asked Jul 24 '13 05:07

Jakub Holovsky


1 Answers

After mapping you will have mapped object without any references to source entity (which holds database context for lazy loading). Only property values are copied to destination entity. So you will not be able to do any lazy-loading without source entity.

Actually lazy loading works just fine for you - and it's occur during mapping process. You specified mappings for lazy-loaded properties of your entity, and mapper tries to get those values. That results in lazy-loading all navigation properties which you have configured for mapping. This is very inefficient. To disable lazy-loading during mapping you can ignore navigation properties in mapping configuration. E.g. if you have customer with lazy-loaded orders:

Mapper.CreateMap<Customer, CustomerDto>()
      .ForMember(s => s.Orders, m => m.Ignore());

Or remove Orders property from your destination entity CustomerDto. If you need to have CustomerDto instance with orders inside, then best option is to do eager loading of orders, to avoid additional queries.

like image 82
Sergey Berezovskiy Avatar answered Sep 21 '22 12:09

Sergey Berezovskiy