Is automapper preventing lazy loading with EF?

I use AutoMapper and it seems to get all the child objects (even if I don’t specify them in the "Include ()" section). Is there a way to make lazy loading possible and get child properties only if I specify them.

Thanks,

Jakub

+4
source share
2 answers

After matching, you will have a mapped object without any reference to the original object (which contains the database context for lazy loading). Only property values ​​are copied to the target. Thus, you cannot perform lazy loading without the original entity.

In fact, lazy loading works just fine for you - and this happens during the mapping process. You specified mappings for the lazy properties of your object, and mapper is trying to get these values. This results in lazy loading of all the navigation properties that you configured for mapping. It is very inefficient. To disable lazy loading during matching, you can ignore the navigation properties in the mapping configuration. For instance. if you have a customer with lazy orders:

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

Or remove the Orders property from your CustomerDto target. If you need to have a CustomerDto instance with orders inside, then the best option is to load orders in order to avoid additional requests.

+8
source

I think the best way is to define your matching objects according to your needs. Only the required child entities are defined in the mapping object. Say some DTOs like this map to the Person object in the domain.

 class PersonDto { public string Name{get;set;} public PersonLiteDto Parent{get; set;} } class PersonLiteDto { public string Name{get;set;} //no navigation properties here.. } 
+2
source

Source: https://habr.com/ru/post/1493108/


All Articles