About AsQueryable
-
Sunday, January 20, 2013 12:48 PM
What is the purpose of "AsQueryable"?
All I was able to glean from monkeying around with the method is that it allows to convert from "IEnumerable" back to "IQueryable" but that seems like a pointless conversion (at least I see no use for it). All the explanations I;'ve found sounded too "academic" without examples.
I only see some use in the following example:
dc.Customers.AsEnumerable().Where(c => c.CompanyName == "The Big Cheese").ToList();
it runs this SQL:
SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName], [t0].[ContactTitle], [t0].[Address], [t0].[City], [t0].[Region], [t0].[PostalCode], [t0].[Country], [t0].[Phone], [t0].[Fax] FROM [dbo].[Customers] AS [t0]
And if we convert to "AsQueryable" then the result drastically changes:
exec sp_executesql N'SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName], [t0].[ContactTitle], [t0].[Address], [t0].[City], [t0].[Region], [t0].[PostalCode], [t0].[Country], [t0].[Phone], [t0].[Fax] FROM [dbo].[Customers] AS [t0] WHERE [t0].[CompanyName] = @p0',N'@p0 nvarchar(4000)',@p0=N'The Big Cheese'
But we didn't even have to convert to "IEnumerable" in the first place, so this use of "AsQueryable" seems pointless.
Could you give me a better example, where the use of "AsQueryable" would be really indispensable?
Thanks!
All Replies
-
Monday, January 21, 2013 8:22 AM
Have you read this explanation from MSDN?
http://msdn.microsoft.com/en-us/library/system.linq.iqueryable.aspx
Also here is one more article, some additional explanation, more use cases and some fun.
http://www.weirdlover.com/2010/05/11/iqueryable-can-kill-your-dog-steal-your-wife-kill-your-will-to-live-etc/
Do you also had a question after this explanation?
Please Mark as Reply and Vote as Helpful if I helped.
Also please visit my blog http://msguy.net/- Edited by Michael Samteladze Monday, January 21, 2013 8:24 AM
- Marked As Answer by Alexander SunModerator Wednesday, January 30, 2013 8:37 AM
-
Monday, January 21, 2013 8:39 AMHi
IQueryable interface actually is intended when you map your exact LINQ query to SQL including all conditions and other constructs that may have been added in the LINQ query. This actually optimizes the actual SQL query that hits the database. These are all implemented by specific data providers.
Hope this helps.One good question is equivalent to ten best answers.

