Is there a way to get the SQL created by a LINQ query?
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:
- Use LINQPad
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
精彩评论