Debugging Entity Framework SQL statements

前端 未结 2 376
终归单人心
终归单人心 2020-12-03 14:56

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

This is from my web host:

This is from my local

相关标签:
2条回答
  • 2020-12-03 15:55

    In EF6, you can also do this in the constructor of your dbcontext

    Example

    public BookServiceContext() : base("name=BookServiceContext")
    {
        // New code:
        this.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
    }
    

    This will log to the console every SQL query EF generates. See this article for more information http://blog.oneunicorn.com/2013/05/08/ef6-sql-logging-part-1-simple-logging/

    0 讨论(0)
  • 2020-12-03 15:58

    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).

    0 讨论(0)
提交回复
热议问题