Question

If I dont' wrong, I can get the data from a database in to ways:

  1. First with an IEnumerable:

    myContext.MyTable.ToList();

  2. With an IQeryable:

    IQueryable<MyTable> query = myContext.Mytable;

I know that one of the advantages is that IQueryable execute the conditions in the server, so is more efficient and faster that IEnumerable.

But In my repository, as I return a List, I would like to know if this:

return query.ToList();

has the advantages of the IQueryable.

Was it helpful?

Solution

query.ToList() is the same like myContext.MyTable.ToList(). It returns a collection in memory (the whole database table) and is just an IEnumerable<T>, not an IQueryable<T>. Every further LINQ operator - for example a Where clause - you append, will be performed in memory and not in the database.

If you choose to return IEnumerable<T> or List<T> from your repository you have to design the repository methods so that you can apply filters, sorting, etc. inside of those methods - for example by passing in filter and sort expressions as parameters into the methods or by creating lots of specialized methods for different use cases - like GetOrdersByCustomerId, GetOrdersByShippingDate, etc., etc. If you do it outside of and after calling repository methods you will suffer from poor performance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top