Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to find the LINQ statement for a SQL statement

I am a SQL Server DBA for a company that sells an ASP.NET MVC3 application that uses LINQ and Entity Framework 4 for all database access. When I find an inefficient query in my SQL Server's plan cache that was generated by LINQ, I would like to be able to find that LINQ statement in the source code so that I can optimize it. What is the best way to find the LINQ that generated a given SQL statement?

For example, is there any way to put an entry in a config file or decorate the code somehow so that the class and method name or the LINQ statement itself are included as comments in the generated SQL?

like image 564
Mark Freeman Avatar asked Nov 04 '11 15:11

Mark Freeman


People also ask

How can I see the LINQ query in SQL Profiler?

Now, let's run the Application and run the trace in SQL Server Profiler. Click on Get Data button, the data will be populated on the page. Go to SQL Server Profiler and stop the trace, where you will see T-SQL statement of our stored procedure, as shown below. Notice that GetEmployees stored procedure is executed.

What is LINQ in SQL?

LINQ to SQL is a component of . NET Framework version 3.5 that provides a run-time infrastructure for managing relational data as objects. Relational data appears as a collection of two-dimensional tables (relations or flat files), where common columns relate tables to each other.

What is the LINQ equivalent to the SQL IN operator?

An IEnumerable<T>.


2 Answers

The commercial tools ORM Profiler, Entity Framework Profiler or Hugati Query Profiler will both give you a stack trace for the methods which generated the SQL. That makes it fairly easy to find the LINQ in code, though it isn't displayed directly.

These tools also have the advantage that they make it easy to find inefficient queries amongst the many other SQL statements executed by the app.

like image 189
Craig Stuntz Avatar answered Oct 13 '22 10:10

Craig Stuntz


Although it is not a free tool, this may provide the information you need:

http://efprof.com/

There is also a less expensive tool described here, which I have not used, but it looks very promising:

http://huagati.blogspot.com/2010/06/entity-framework-support-in-huagati.html

http://www.huagati.com/L2SProfiler/

like image 28
hatchet - done with SOverflow Avatar answered Oct 13 '22 10:10

hatchet - done with SOverflow