Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve LINQ to sql statement (IQueryable) WITH parameters

Tags:

c#

linq-to-sql

I'm trying to figure out if there's a way to retrieve the (full) sql statement that gets executed on the database server.
I found something already, but it does not exactly what I would like:

IQueryable<SomeType> someQuery = ... string command = dataContext.GetCommand(query).CommandText; 

In my case this gives me a command string something like:

SELECT TOP (50) [t0].[ID], .... FROM [dbo].[someTable] AS [t0] WHERE ([t0].[someColumn] IS NOT NULL) AND (([t0].[someColumn]) IN (@p0)) 

On database there's executed:

exec sp_executesql N'SELECT TOP (50) [t0].[ID], ... FROM [dbo].[someTable] AS [t0] WHERE ([t0].[someColumn] IS NOT NULL) AND (([t0].[someColumn]) IN (@p0, @p1))',N'@p0  int,@p1 int',@p0=401,@p1=201 

Is there a way to retrieve this 'full' statement (so also the parameter values) from C# code?

like image 645
TweeZz Avatar asked Jun 14 '11 12:06

TweeZz


People also ask

Is LINQ converted to SQL?

LINQ parses C# language expression into a SQL Server query that is sent to the database to execute. However, the query is not sent and accessed until you actually enumerate over the data.

What inherits from IQueryable?

The IQueryable interface inherits the IEnumerable interface so that if it represents a query, the results of that query can be enumerated. Enumeration causes the expression tree associated with an IQueryable object to be executed.

What does LINQ query return?

By default, LINQ queries return a list of objects as an anonymous type. You can also specify that a query return a list of a specific type by using the Select clause.


1 Answers

You can also see the generated sql query if you have an instance of IQueryable<T> and call the .ToString() method.
For Example:

var db = new DbContext(); IQueryable<Blog> query = db.Blog.Where(tt=> tt.Id > 100).OrderByDescending(tt=>tt.Id); var sqlString = query.ToString(); Console.WriteLine(sqlString); 

This will generate an output of:

SELECT [Extent1].[Id] AS [Id],  [Extent1].[Title] AS [Title],  [Extent1].[Author] AS [Author],  [Extent1].[Text] AS [Text],  [Extent1].[CreatedAt] AS [CreatedAt],  [Extent1].[UpdatedAt] AS [UpdatedAt] FROM [dbo].[Blogs] AS [Extent1] WHERE [Extent1].[Id] > 100 ORDER BY [Extent1].[Id] DESC 
like image 56
Nick Polyderopoulos Avatar answered Sep 28 '22 12:09

Nick Polyderopoulos