前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ADO.NET Entity Framework CodeFirst 如何输出日志(EF 5.0)

ADO.NET Entity Framework CodeFirst 如何输出日志(EF 5.0)

作者头像
张善友
发布2018-01-29 15:17:45
5580
发布2018-01-29 15:17:45
举报
文章被收录于专栏:张善友的专栏张善友的专栏

ADO.NET Entity Framework CodeFirst 如何输出日志(EF4.3) 用的EFProviderWrappers ,这个组件好久没有更新了,对于SQL执行日志的解决方案的需求是杠杠的,今天给大家介绍一个更好的组件Clutch.Diagnostics.EntityFramework,可以通过Nuget 获取:

image
image

这个框架定义了一个接口 IDbTracingListener:

代码语言:javascript
复制
namespace Clutch.Diagnostics.EntityFramework
{

  public interface IDbTracingListener
  {

    void CommandExecuting(DbTracingContext context);

    void CommandFinished(DbTracingContext context);

    void ReaderFinished(DbTracingContext context);

    void CommandFailed(DbTracingContext context);

    void CommandExecuted(DbTracingContext context);

  }
}

实现这个接口,添加一个类,里面实现自己的SQL 日志记录:

代码语言:javascript
复制
using System;
using System.Data.Common;
using System.Diagnostics;
using Clutch.Diagnostics.EntityFramework;

/// <summary>
/// Implementation of IDbTracingListener Class is used for tracing all SQL Queries to the entity framework database
/// </summary>
public class DbTracingListener : IDbTracingListener
{
    public void CommandExecuted(DbConnection connection, DbCommand command, object result, TimeSpan duration)
    {
        Debug.WriteLine(command.CommandText);
        Debug.WriteLine(string.Format("Executed in: {0}", duration));
    }

    public void CommandExecuting(DbConnection connection, DbCommand command)
    {

    }

    public void CommandFailed(DbConnection connection, DbCommand command, Exception exception, TimeSpan duration)
    {

    }

    public void CommandFinished(DbConnection connection, DbCommand command, object result, TimeSpan duration)
    {

    }
}

在方法内部通过 context.Command.CommandText 可以获得你的ef的sql命令的内容。

然后在程序的入口启用SQL日志输出实现:

代码语言:javascript
复制
// Enable Tracing queries
DbTracing.Enable();
// Adding the listener (implementation of IDbTracingListener)
DbTracing.AddListener(new DbTracingListener());
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2013-08-08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档