Is automapper preventing lazy loading with EF?

2019-01-20 11:25发布

问题:

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

回答1:

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.



回答2:

I think the best way is to define your mapping objects according to your need. In the mapping object define only the needed child entities.Let's say some DTOs like this mapping in to the Person entity 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..
}