Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debugging Entity Framework SQL statements

I am having a weird pattern of response time when using the Entity Framework for SQL communication.

This is from my web host:

enter image description here

This is from my local server:

enter image description here

It's the increase in response time I am worried about. I have narrowed the problem down to one single line in code Nop.Data > EfRepository.cs > public void Insert(T entity) > _entities.Add(entity); Yes I know this very specific for the NopCommerce, but the point is really that I am looking her for help on how to debug this.

Are there some events I can catch that display the SQL being executed? Or what other things can I do to find out more what is actually happening in the Entity Framework in that above command.

like image 216
Anders Avatar asked Oct 26 '11 11:10

Anders


People also ask

Can we use SQL query in Entity Framework?

In Entity Framework you can query with your entity classes using LINQ. You can also run queries using raw SQL directly against the database using DbCOntext. The techniques can be applied equally to models created with Code First and EF Designer.

How you debug SQL query?

You can start the Transact-SQL debugger after you open a Database Engine Query Editor window. Then, you can run your Transact-SQL code in debug mode until you stop the debugger. You can set options to customize how the debugger runs. This feature works with SSMS version 17.9.


1 Answers

For debugging EF queries, the easiest thing is to cast the query to ObjectQuery and use ToTraceString:

var query = myContext.MyTable
    .Where(r => r.Id == searchId)
    .Select(r => r);

Console.WriteLine(((ObjectQuery)query).ToTraceString());

This will show the underlying SQL for the query, and you can run the queries manually to debug why they are slow. Here is the MSDN link:

http://msdn.microsoft.com/en-us/library/system.data.objects.objectquery.totracestring.aspx

If you're trying to get the SQL which is run when you call SaveChanges() on your context, it's not as easy. You could take a look at EFTracingProvider:

http://blogs.msdn.com/b/jkowalski/archive/2009/06/11/tracing-and-caching-in-entity-framework-available-on-msdn-code-gallery.aspx

Or, assuming you use SQL Server, you can go directly to SQL Profiler and capture the T-SQL statements (this is my preferred approach).

like image 173
JohnD Avatar answered Oct 12 '22 23:10

JohnD