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


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

    image

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

    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 日志记录:
    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日志输出实现:

    // Enable Tracing queries
    DbTracing.Enable();
    // Adding the listener (implementation of IDbTracingListener)
    DbTracing.AddListener(new DbTracingListener());
  • 相关阅读:
    工具:统计jQuery中各字符串出现次数
    读Ext之八(原生事件对象的修复及扩充)
    querySelector和getElementById通过id获取元素的区别
    读Ext之十(解析JSON)
    Safari/Chrome中placeholder属性实现不完整
    读Ext之十一(通过innerHTML创建元素)
    各浏览器中innerHTML实现差异(2)
    读Ext之五(Dom的低级封装)
    读Ext之十二(在各个位置插入元素)
    读Ext之四(事件的低级封装)
  • 原文地址:https://www.cnblogs.com/shanyou/p/3246992.html
Copyright © 2020-2023  润新知