【问题标题】:How to log SQL using entity framework 4.3 (code first) and SQL Azure database如何使用实体框架 4.3(代码优先)和 SQL Azure 数据库记录 SQL
【发布时间】:2012-03-06 08:04:35
【问题描述】:

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

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

我使用了Entity Profiler Framework,虽然这在开发过程中很有帮助,但我不确定它在生产过程中是否有用。

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

我已尝试使用 EFTracingProvider 并按照here 中的步骤操作。不幸的是,当我尝试执行我的第一个命令(使用适当的联合)时,我收到一个异常,指出“不支持指定的方法”。

产生错误的代码如下:

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

所以这是我的问题:

  • EFTracingProvider 是记录 SQL 查询(全局)的首选方法吗?
  • 如果是这样,您知道为什么会出现上述异常吗?
  • 如果没有,是否有其他机制可以让我记录实体框架生成的所有 SQL?

感谢您的帮助, 埃里克

【问题讨论】:

    标签: entity-framework ef-code-first azure-sql-database


    【解决方案1】:

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

    创建以下类:

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

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

    【讨论】:

    • 这似乎也是作者推荐的。 Here 在“已知问题”中他们说要通过 context.Connection.GetStoreConnection().CreateCommand() 执行存储命令。如此有效地做你所做的并使用包装的连接:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多