文章出處
文章列表
ADO.NET Entity Framework CodeFirst 如何輸出日志(EF4.3) 用的EFProviderWrappers ,這個組件好久沒有更新了,對于SQL執行日志的解決方案的需求是杠杠的,今天給大家介紹一個更好的組件Clutch.Diagnostics.EntityFramework,可以通過Nuget 獲取:
這個框架定義了一個接口 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());
文章列表
全站熱搜