Reputation: 21178
I'm getting into using the Repository Pattern for data access with the Entity Framework and LINQ as the underpinning of implementation of the non-Test Repository. Most samples I see return AsQueryable() when the call returns N records instead of List<T>. What is the advantage of doing this?
Upvotes: 63
Views: 64043
Reputation: 1
IQueryable
:IEnumerable
: Is eager loading thus records will be loaded first in-memory operation and then the operation will be performed.So depending on use case like while paging on a huge number of records we should use IQueryable<T>
provided that DBcontext is open till the execution, if short operation and doesn't create huge memory storage you can go with IEnumerable
.
Upvotes: -1
Reputation: 4297
AsQueryable
is an extension method for IEnumerable<T>
that could do two things:
IEnumerable<T>
implements IQueryable<T>
justs casts, doing nothing. IEnumerable<T>
(EnumerableQuery<T>
) that implements every method compiling the lambdas and calling to Enumerable extension methods. So in most of the cases using AsQueryable is useless, unless u are forced to pass a IQueryable to a method and u have a IEnumerable instead, it's a hack.
NOTE: AsQueryable is a hack, IQueryable of course is not!
Upvotes: 13
Reputation: 59705
Returning IQueryable<T>
has the advantage, that the execution is defferer until you really start enumerating the result and you can compose the query with other queries and still get server side execution.
The problem is that you cannot control the lifetime of the database context in this method - you need an open context and must ensure that it stays open until the query gets executed. And then you must ensure that the context will be disposed. If you return the result as a List<T>
, T[]
, or something similar, you loose deffered execution and server side execution of composed queries, but you win control over the lifetime of the database context.
What fits best, of course, depends on the actual requirements. It's another question without a single truth.
Upvotes: 27
Reputation: 77590
Returning IQueryable<T>
will defer execution of the query until its results are actually used. Until then, you can also perform additional database query operations on the IQueryable<T>
; on a List
you're restricted to generally less-efficient in-memory operations.
Upvotes: 4
Reputation: 70327
AsQueryable just creates a query, the instructions needed to get a list. You can make futher changes to the query later such as adding new Where clauses that get sent all the way down to the database level.
AsList returns an actual list with all the items in memory. If you add a new Where cluse to it, you don't get the fast filtering the database provides. Instead you get all the information in the list and then filter out what you don't need in the application.
So basically it comes down to waiting until the last possible momment before committing yourself.
Upvotes: 111