Query Return - Generic Entity Framework Repository

Asked

Viewed 219 times

4

I have a generic repository and I realized that it is taking too long to return a query with the selection of some columns of my database, the Query() method is as follows:

public IList<T> Query(System.Linq.Expressions.Expression<Func<T, bool>> Where)
    {
        return Entity.AsExpandable().Where(Where).AsQueryable<T>().AsNoTracking<T>().ToList();
    }

If you observe at the end I still use Take(10), but analyzing the code, there is a field called 'source' that shows 17822 records, so regardless of selecting 10 or 1000, it seems to me that it is always bringing all the records, follows image:

inserir a descrição da imagem aqui

My question is whether I’m with some Entity configuration to always have this behavior or my query call is wrong?

Thank you

Leo

  • where are you using the Skip and Take, before or after theToList?

  • I’m using take after Tolist

  • 1

    When you use the ToList it brings the result, then filtering with Take, so it’s bringing "everything". You can leave the ToList to the end to settle this

1 answer

4


Basically your problem is that when you use the skip and take after the toList(), the EF has gone to the comic book, brought all these records, and the skip and take are happening in memory.

I understand you need to make yours take(10), out of the repository, then I suggest the following change in its function:

public IQueryable<T> 
Query(System.Linq.Expressions.Expression<Func<T, bool>> Where)
{
    return Entity.AsExpandable().Where(Where).AsNoTracking<T>();
}
  • We removed the .AsQueryable<T>(), for AsNoTracking<T>(), já te retornaQueryable(T)`. this already helps you a little bit of the performance.
  • We removed the ToList(), so that the EF does not go to the database at this very moment, we are just creating its Query, which will be returned. So you would make use of the Query as follows:

var resultadoDaQuery = Query(seyWhere).Skip(skipRows).Take(pageSize).ToList();
  • At present, when we use the method ToList(), the EF goes to the database, bringing only the records, considering your Skip() and Take().
  • 3

    Another way to explain the difference is: in LINQ there are some commands that actually execute the query and bring to memory (Tolist, First, Last, Count), otherwise, the object will be Iqueryable, ie, just a query that, while not receiving one of the commands mentioned above, is not executed at the bank.. That is, you first manipulate your query, filter, group, add and finally, run.

  • Great observation @M.Bertolazo

  • 1

    @Rodrigok. B If the return of the method is IList<T> will make no difference. The query will be executed the same way.

  • @LINQ thanks for the remark, it was my lack of attention. I will correct.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.