Search code examples
c#.netentity-framework.net-coreautomapper

Backend data filtering. EF with mapping to DTO


I'm using EF core with automapper and I need to do data filtering, that depends on frontend.

My question is what will be the right sequence:

  1. Get entries -> do filtering -> convert to DTO
var query = dbContext.Tasks
      .AsNoTracking();

    if (paginationMeta.From != null)
    {
      query = query.Where(x => x.Date > paginationMeta.From);
    }

return query.ToList()

or

  1. Get entries -> convert to DTO -> do filtering
var query = dbContext.Tasks
       .ProjectTo<DTO>()
      .AsNoTracking();

    if (paginationMeta.From != null)
    {
      query = query.Where(x => x.DateMapped > paginationMeta.From);
    }

return query.ToList()

Convert to DTO first seems more convenient way but in case of complicated mapping it leads to slower execution

How do you usually do that?


Solution

  • From AutoMapper’s Queryable Extensions docs:

    ProjectTo must be the last call in the chain. ORMs work with entities, not DTOs. So apply any filtering and sorting on entities and, as the last step, project to DTOs.

    So the correct one is the first (I even doubt that the second one will work, as far as I remember it should result in an exception).