views:

3481

answers:

4

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. Could someone tell me the advantage of doing this?

Regards

+14  A: 

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.

Jonathan Allen
agree, but remember that beyond the "fast filtering", there is also the hit of sending all that info through the network.
eglasius
Also, its not the only way to do it, as u could receive the filters to apply instead of returning something that can be filtered. The first is easier to use if u later move from using a db to something else i.e. a web service or anything else.
eglasius
Another point: if you return an IQueryable you must find a good way to ensure that 1.) the context is open until the query gets executed and 2.) that the context will correctly disposed. Returning a list has the advantage that you can control the lifetime of the context inside a method. What fits better depends on the actual requirements.
Daniel Brückner
+3  A: 

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.

dahlbyk
I think that's what Grauenwolf already said :P :)
eglasius
His answer was submitted while I wrote mine. :)
dahlbyk
+6  A: 

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.

Daniel Brückner