jamone
jamone

Reputation: 17419

Is there a way to get the SQL created by a LINQ query?

I've been developing a ASP.NET page and have been using LINQ to handle talking to MS SQL server. I'm ok at basic SQL, however I'm a lot better with designing queries using LINQ. I know they are similar but I find it easer to design complex queries in LINQ. My question is this: Is there a way to design a query in LINQ and then get the SQL that it generated? I would like to embed the SQL in a stored procedure since multiple pages (outside my control) will need to do the same query.

Upvotes: 5

Views: 229

Answers (4)

James Fleming
James Fleming

Reputation: 2589

When writing linq statements that are executed against SQL Server, Always eyeball them in SQL Server Profiler. The interpretation that is executed inside of SQL will often surprise you.

In performance tools/SQL Server Profiler start a new trace.

Execute your query in your app, grab the output from Profiler Paste into SQL Server query analyzer

Upvotes: 1

Giorgi
Giorgi

Reputation: 30893

If you want to get more in-depth information then you can use Linq to Sql Profiler which will display all queries as well as alerts

Upvotes: 1

Marcel Gosselin
Marcel Gosselin

Reputation: 4716

You can get it 2 ways:

  1. Use LINQPad
  2. use ToString() on the query to get its SQL form:

    var query = from x in SomeTable where x.SomeField == 5 select x.SomeOtherField; Console.WriteLine(query.ToString());

Upvotes: 3

Randy Minder
Randy Minder

Reputation: 48522

Yes. The LINQ database context has a Log property that outputs the SQL it executed. You can also do this through a free product called LinqPad and a commercial product named Linqer.

Upvotes: 6

Related Questions