Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

sql

asp.net

linq

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.

like image 618
jamone Avatar asked Jan 18 '10 19:01

jamone


3 Answers

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.

like image 142
Randy Minder Avatar answered Sep 25 '22 11:09

Randy Minder


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

like image 29
Marcel Gosselin Avatar answered Sep 25 '22 11:09

Marcel Gosselin


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

like image 42
Giorgi Avatar answered Sep 25 '22 11:09

Giorgi