tags:

views:

104

answers:

4

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.

+6  A: 

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.

Randy Minder
You can also use DataContext.GetCommand(query).
itowlson
+3  A: 

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());

Marcel Gosselin
+1  A: 

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

Giorgi
+1  A: 

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

James Fleming