How to log SQL using entity framework 4.3 (code first) and SQL Azure database

妖精的绣舞 提交于 2020-01-03 15:34:36

问题


I realize this similar question has been asked a few times, and I have tried the recommendations in those questions without success.

I am using the entity framework (4.3) and running against SQL Azure (on a federated database). I'd like to be able to log the SQL that is being generated by the entity framework.

I've used the Entity Profiler Framework and while that is helpful during development, I am not sure it would be helpful during production.

I can't use SQL Profiler as this is a SQL Azure database.

I've tried using the EFTracingProvider and following the steps in here. Unfortunately, when I attempt to execute my first command (which is using the appropriate federation), I get an exception indicating that the "Specified method is not supported."

The code which generates the error is the following:

public MyContext(int tenantId) 
    : base(CreateTracingConnection("TheDb"), true)
{
    const string FederationCmdText =
        "USE FEDERATION TenantFederation(CustomerId = {0}) WITH RESET, FILTERING=ON";

    ((IObjectContextAdapter)this).ObjectContext.EnableTracing();

    ((IObjectContextAdapter)this).ObjectContext.Connection.Open();

    // This is the line which throws the exception
    this.Database.ExecuteSqlCommand(string.Format(FederationCmdText, tenantId));        
}

Here's the exception:

Specified method is not supported.
at EFProviderWrapperToolkit.DbConnectionWrapper.CreateDbCommand()
at System.Data.Common.DbConnection.CreateCommand()
...

So here are my questions:

  • Is EFTracingProvider the preferred approach for logging SQL queries (globally)?
  • If so, any ideas why I am getting the above exception?
  • If not, is there another mechanism that will allow me to log all of the SQL generated by the Entity Framework?

Thanks for your help, Eric


回答1:


The issue that I was running into was because, I believe, the EFTracingProvider does not have support for executing SQL directly. In order to workaround that issue, one solution is the following (which I found in the Q&A from here)

Create the following class:

public class DbTracingConnection : EFTracingConnection
{
    protected override DbCommand CreateDbCommand()
    {
        return this.WrappedConnection.CreateCommand();
    }
}

When creating the connection, use the above class instead of the EFTracingConnection.



来源:https://stackoverflow.com/questions/9285621/how-to-log-sql-using-entity-framework-4-3-code-first-and-sql-azure-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!