实体框架 4.1 - EFTracingProvider

发布于 2024-11-03 12:18:22 字数 162 浏览 0 评论 0原文

有没有办法让 EFTracing 提供程序与 EF 4.1 配合使用?

EFTracing 似乎需要一个对象上下文,我使用 dbcontext。

提前致谢!

Is there a way to make the EFTracing provider work with EF 4.1?

EFTracing seems to need an objectcontext and I use dbcontext.

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

七堇年 2024-11-10 12:18:22

是的,你可以。我正在使用 社区版本 以及数据库优先 DbContext 和代码优先 DbContext。此答案基于项目网站上的讨论主题

对于数据库优先/设计器 DbContext(通过 ADO.NET DbContext 生成器模板),您可以简单地添加以下构造函数:

public abstract class MyDbContext : DbContext
{
    protected MyDbContext(string nameOrConnectionString)
        : base(EFTracingProviderUtils.CreateTracedEntityConnection(nameOrConnectionString), true)
    {
        // enable sql tracing
        ((IObjectContextAdapter) this).ObjectContext.EnableTracing();
    }
}

对于代码优先的 DbContexts,它有点复杂,因为 EFTracingProvider 需要完整的实体连接字符串。您必须手动创建 EFTracingConnection 的实例。以下示例适用于数据库优先和代码优先上下文。

public abstract class MyDbContext : DbContext
{
    protected MyDbContext(string nameOrConnectionString)
        : base(CreateTracingConnection(nameOrConnectionString), true)
    {
        // enable sql tracing
        ((IObjectContextAdapter) this).ObjectContext.EnableTracing();
    }

    private static DbConnection CreateTracingConnection(string nameOrConnectionString)
    {
        try
        {
            // this only supports entity connection strings http://msdn.microsoft.com/en-us/library/cc716756.aspx
            return EFTracingProviderUtils.CreateTracedEntityConnection(nameOrConnectionString);
        }
        catch (ArgumentException)
        {
            // an invalid entity connection string is assumed to be a normal connection string name or connection string (Code First)

            ConnectionStringSettings connectionStringSetting =
                ConfigurationManager.ConnectionStrings[nameOrConnectionString];
            string connectionString;
            string providerName;

            if (connectionStringSetting != null)
            {
                connectionString = connectionStringSetting.ConnectionString;
                providerName = connectionStringSetting.ProviderName;
            }
            else
            {
                providerName = "System.Data.SqlClient";
                connectionString = nameOrConnectionString;
            }

            return CreateTracingConnection(connectionString, providerName);
        }
    }

    private static EFTracingConnection CreateTracingConnection(string connectionString, string providerInvariantName)
    {
        // based on the example at http://jkowalski.com/2010/04/23/logging-sql-statements-in-entity-frameworkcode-first/
        string wrapperConnectionString =
            String.Format(@"wrappedProvider={0};{1}", providerInvariantName, connectionString);

        EFTracingConnection connection =
            new EFTracingConnection
                {
                    ConnectionString = wrapperConnectionString
                };

        return connection;
    }
}

Yes, you can. I'm using the community version with both database-first DbContexts and code-first DbContexts. This answer is based on a discussion thread on the project site.

For database-first/designer DbContexts (via ADO.NET DbContext Generator templates), you can simply add the following constructor:

public abstract class MyDbContext : DbContext
{
    protected MyDbContext(string nameOrConnectionString)
        : base(EFTracingProviderUtils.CreateTracedEntityConnection(nameOrConnectionString), true)
    {
        // enable sql tracing
        ((IObjectContextAdapter) this).ObjectContext.EnableTracing();
    }
}

For code first DbContexts its a bit more complicated since the EFTracingProvider wants a full entity connection string. You have to create an instance of EFTracingConnection manually. The following example will work for both database first and code first contexts.

public abstract class MyDbContext : DbContext
{
    protected MyDbContext(string nameOrConnectionString)
        : base(CreateTracingConnection(nameOrConnectionString), true)
    {
        // enable sql tracing
        ((IObjectContextAdapter) this).ObjectContext.EnableTracing();
    }

    private static DbConnection CreateTracingConnection(string nameOrConnectionString)
    {
        try
        {
            // this only supports entity connection strings http://msdn.microsoft.com/en-us/library/cc716756.aspx
            return EFTracingProviderUtils.CreateTracedEntityConnection(nameOrConnectionString);
        }
        catch (ArgumentException)
        {
            // an invalid entity connection string is assumed to be a normal connection string name or connection string (Code First)

            ConnectionStringSettings connectionStringSetting =
                ConfigurationManager.ConnectionStrings[nameOrConnectionString];
            string connectionString;
            string providerName;

            if (connectionStringSetting != null)
            {
                connectionString = connectionStringSetting.ConnectionString;
                providerName = connectionStringSetting.ProviderName;
            }
            else
            {
                providerName = "System.Data.SqlClient";
                connectionString = nameOrConnectionString;
            }

            return CreateTracingConnection(connectionString, providerName);
        }
    }

    private static EFTracingConnection CreateTracingConnection(string connectionString, string providerInvariantName)
    {
        // based on the example at http://jkowalski.com/2010/04/23/logging-sql-statements-in-entity-frameworkcode-first/
        string wrapperConnectionString =
            String.Format(@"wrappedProvider={0};{1}", providerInvariantName, connectionString);

        EFTracingConnection connection =
            new EFTracingConnection
                {
                    ConnectionString = wrapperConnectionString
                };

        return connection;
    }
}
樱花落人离去 2024-11-10 12:18:22

虽然前面的答案有效,但我发现它们存在问题,一个更简单的解决方案是使用 NuGet 中的 Clutch.Diagnostics.EntityFramework 包,该包在幕后使用 MiniProfiler。与 EFTracingProvider 相比,它的使用起来要简单得多,并且是一个更加灵活的解决方案。

该项目位于 GitHub 上 https://github.com/Kukkimonsuta/Clutch

对于 EFTracingProvider 之类的功能,请安装 NuGet 包,然后实施IDbTracingListener 像这样:

using System;
using System.Data.Common;
using System.Diagnostics;
using Clutch.Diagnostics.EntityFramework;

/// <summary>
/// 
/// </summary>
public class DbTracingListener : IDbTracingListener
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="connection"></param>
    /// <param name="command"></param>
    /// <param name="result"></param>
    /// <param name="duration"></param>
    public void CommandExecuted(DbConnection connection, DbCommand command, object result, TimeSpan duration)
    {
        Debug.WriteLine(command.CommandText);
        Debug.WriteLine(string.Format("Executed in: {0}", duration));
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="connection"></param>
    /// <param name="command"></param>
    public void CommandExecuting(DbConnection connection, DbCommand command)
    {

    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="connection"></param>
    /// <param name="command"></param>
    /// <param name="exception"></param>
    /// <param name="duration"></param>
    public void CommandFailed(DbConnection connection, DbCommand command, Exception exception, TimeSpan duration)
    {

    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="connection"></param>
    /// <param name="command"></param>
    /// <param name="result"></param>
    /// <param name="duration"></param>
    public void CommandFinished(DbConnection connection, DbCommand command, object result, TimeSpan duration)
    {

    }
}

Whilst the previous answers work, I've found them problematic, a much simpler solution is to use the Clutch.Diagnostics.EntityFramework package from NuGet that uses MiniProfiler behind the scenes. It is significantly simpler to get working than EFTracingProvider, and a much more flexible solution.

The project is on GitHub at https://github.com/Kukkimonsuta/Clutch

For EFTracingProvider like functionality install the NuGet package and then implement IDbTracingListener like this:

using System;
using System.Data.Common;
using System.Diagnostics;
using Clutch.Diagnostics.EntityFramework;

/// <summary>
/// 
/// </summary>
public class DbTracingListener : IDbTracingListener
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="connection"></param>
    /// <param name="command"></param>
    /// <param name="result"></param>
    /// <param name="duration"></param>
    public void CommandExecuted(DbConnection connection, DbCommand command, object result, TimeSpan duration)
    {
        Debug.WriteLine(command.CommandText);
        Debug.WriteLine(string.Format("Executed in: {0}", duration));
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="connection"></param>
    /// <param name="command"></param>
    public void CommandExecuting(DbConnection connection, DbCommand command)
    {

    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="connection"></param>
    /// <param name="command"></param>
    /// <param name="exception"></param>
    /// <param name="duration"></param>
    public void CommandFailed(DbConnection connection, DbCommand command, Exception exception, TimeSpan duration)
    {

    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="connection"></param>
    /// <param name="command"></param>
    /// <param name="result"></param>
    /// <param name="duration"></param>
    public void CommandFinished(DbConnection connection, DbCommand command, object result, TimeSpan duration)
    {

    }
}
夏至、离别 2024-11-10 12:18:22

如果您使用 DBContext 和 MVC Model First,即使用 EntityConnections,那么您只需要以下示例代码:

    public partial class BrickHouseFitnessContext : DbContext
{

    public BrickHouseFitnessContext(): base(EntityConnectionWrapperUtils.CreateEntityConnectionWithWrappers(ConfigurationManager.ConnectionStrings["BrickHouseFitnessContext"].ConnectionString, "EFTracingProvider"), true)
    {
    }

另外:

在 Web.Config 文件中添加以下部分:

  <system.data>
<DbProviderFactories>
  <add name="EF Tracing Data Provider" invariant="EFTracingProvider" description="Tracing Provider Wrapper" type="EFTracingProvider.EFTracingProviderFactory, EFTracingProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=def642f226e0e59b" />
  <add name="EF Generic Provider Wrapper" invariant="EFProviderWrapper" description="Generic Provider Wrapper" type="EFProviderWrapperToolkit.EFProviderWrapperFactory, EFProviderWrapperToolkit, Version=1.0.0.0, Culture=neutral, PublicKeyToken=def642f226e0e59b" />
</DbProviderFactories>

并且:

    <add key="EFTracingProvider.logToConsole" value="true" />
<add key="EFTracingProvider.logToFile" value="C:\BrickHouseFitnessSqlLog.txt" />

无需包含原文章中提到的 ExtendedEntities 或其他 ObjectContext 派生类。运行该代码,您应该会看到指定的日志文件,其中包含所有 SQL 命令。当启用跟踪时,我绕过数据库初始化,

If you are using DBContext and MVC Model First, meaning using EntityConnections then the following sample code should be all you need:

    public partial class BrickHouseFitnessContext : DbContext
{

    public BrickHouseFitnessContext(): base(EntityConnectionWrapperUtils.CreateEntityConnectionWithWrappers(ConfigurationManager.ConnectionStrings["BrickHouseFitnessContext"].ConnectionString, "EFTracingProvider"), true)
    {
    }

Also:

In the Web.Config file add the following sections:

  <system.data>
<DbProviderFactories>
  <add name="EF Tracing Data Provider" invariant="EFTracingProvider" description="Tracing Provider Wrapper" type="EFTracingProvider.EFTracingProviderFactory, EFTracingProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=def642f226e0e59b" />
  <add name="EF Generic Provider Wrapper" invariant="EFProviderWrapper" description="Generic Provider Wrapper" type="EFProviderWrapperToolkit.EFProviderWrapperFactory, EFProviderWrapperToolkit, Version=1.0.0.0, Culture=neutral, PublicKeyToken=def642f226e0e59b" />
</DbProviderFactories>

and:

    <add key="EFTracingProvider.logToConsole" value="true" />
<add key="EFTracingProvider.logToFile" value="C:\BrickHouseFitnessSqlLog.txt" />

There is no need to include the ExtendedEntities or the other ObjectContext derived class mentioned in the original article. Run that code and you should see your log file as specified, with all the SQL commands in it. I am bypassing database intialization when tracing is enabled,

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文