开发者

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

开发者 https://www.devze.com 2022-12-17 06:09 出处:网络
I\'ve been developing a ASP.NET page and开发者_如何学C 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 kno

I've been developing a ASP.NET page and开发者_如何学C 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.


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.


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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消