Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an api or extension to translate IQueryable<T> lambda expressions to SQL strings?

I was reading an article on Linq to Sql and came across this:

IQueryProvider provider = new QueryProvider(database.GetCommand, database.ExecuteQuery);
IQueryable<Product> source = new Queryable<Product>(provider, database.GetTable<Product>());
IQueryable<string> results = source.Where(product => product.CategoryID == 2)
                                   .OrderBy(product => product.ProductName)
                                   .Select(product => product.ProductName)
                                   .Skip(5)
                                   .Take(10);

The author then translated the results in plain sql:

exec sp_executesql N'SELECT [t1].[ProductName]
FROM (
SELECT ROW_NUMBER() OVER (ORDER BY [t0].[ProductName]) AS [ROW_NUMBER], [t0].[ProductName]
FROM [dbo].[Products] AS [t0]
WHERE [t0].[CategoryID] > @p0
) AS [t1]
WHERE [t1].[ROW_NUMBER] BETWEEN @p1 + 1 AND @p1 + @p2
ORDER BY [t1].[ROW_NUMBER]',N'@p0 int,@p1 int,@p2 int',@p0=2,@p1=5,@p2=10

And I thought to myself, "holy cow! wouldn't it be great if there was an extension to IQueryable that would generate these strings for you when debugging?"

Anyone ever heard of anything like this, and if so, could you point me in the right direction?

Thanks!

like image 370
Christopher Bales Avatar asked Oct 25 '12 15:10

Christopher Bales


3 Answers

With Linq to Sql you can call query.Provider.ToString() and this will return you text of query (btw you can watch same property in Visual Studio when debugging).

UPDATE: (complex part) How it is implemented?

Actual string generation is done by System.Data.Linq.SqlClient.SqlProvider class. It has hidden method string IProvider.GetQueryText(Expression query), which builds SQL query text based on passed expression. This method is hidden by internal interface IProvider, so it's not trivial thing to call it.

like image 147
Sergey Berezovskiy Avatar answered Oct 22 '22 23:10

Sergey Berezovskiy


I think Linqpad can be used to translate between SQL and Linq, hope that helps.

like image 2
DevDave Avatar answered Oct 22 '22 21:10

DevDave


You can set the DataContext.Log property to a TextWriter (e.g. Console.Out) to see the SQL as it is generated, but I don't think this lets you output the SQL without executing it.

like image 2
Rawling Avatar answered Oct 22 '22 23:10

Rawling