Saleh
Saleh

Reputation: 3032

How can i get sql query Equivalent to a linq expression

How can i find out when my program execute a linq expression what sql query has been executed?

Upvotes: 1

Views: 980

Answers (5)

atoMerz
atoMerz

Reputation: 7672

var res = somequery;
Console.WriteLine(res);

Upvotes: 0

Kris Ivanov
Kris Ivanov

Reputation: 10598

  1. you can use SQL Profiler, comes with SQL server install, and capture the statements as they execute
  2. you can use tool like LINQPad and run the LINQ against your data store and examine the SQL within the tool
  3. you can debug your application and get the SQL from the ObjectQuery.ToTraceString method

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1063569

Profiling is a sure way. Depending on the LINQ provider, this may also be inbuilt, for example with LINQ-to-SQL you can assign anything to .Log and it will write the queries as it does them. At the simplest level:

dataContext.Log = Console.Out; // for a LINQ-to-SQL DataContext
// TODO: now execute some queries against dataContext

Internally, we use a custom ADO.NET stack for this (and some other things). It looks like a SqlConnection (and LINQ-to-SQL is perfectly happy with it), but it does some logging and profiling for us on every command executed, so we can see where our long running operations are. I think Sam is looking to make this available to the public if you want.

Upvotes: 2

Guilherme Duarte
Guilherme Duarte

Reputation: 3441

Have you tried LinqPad?

I believe it shows a SQL prototype of your query.

Upvotes: 1

lance
lance

Reputation: 16342

Profiling the database would do it. Keep in mind that the statement won't be executed against the database until your code goes to interrogate the results of the query.

Upvotes: 1

Related Questions