本文介绍了如何使用实体框架4.3(代码优先)和SQL Azure数据库记录SQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到这个类似的问题已经被问了几次,而且我没有成功地尝试过这些问题的建议。

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

我正在使用实体框架(4.3 )并针对SQL Azure运行(在联合数据库上)。我想要能够记录实体框架生成的SQL。

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.

我不能使用SQL Profiler,因为这是一个SQL Azure数据库。

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

我已经尝试使用EFTracingProvider并按照。不幸的是,当我尝试执行我的第一个命令(正在使用适当的联合)时,我收到一个异常,指出指定的方法不受支持。

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

生成错误的代码如下:

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));
}

以下是例外:

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

所以这里是我的问题:


  • EFTracing提供了记录SQL的首选方法查询(全球)?

  • 如果是,任何想法为什么我得到上述例外?

  • 如果没有,是否有另一种机制将允许我记录实体框架生成的所有SQL?

感谢您的帮助,
Eric

Thanks for your help,Eric

推荐答案

我遇到的问题是因为我相信EFTracingProvider不支持直接执行SQL。为了解决这个问题,一个解决方案如下(我在这里的Q& A中找到的) a>)

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)

创建以下类:

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

创建连接时,使用上述类而不是EFTracingConnection。

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

这篇关于如何使用实体框架4.3(代码优先)和SQL Azure数据库记录SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!