Entity Framework 6.X實現記錄執行的SQL功能

来源:http://www.cnblogs.com/godbell/archive/2017/09/12/7512750.html
-Advertisement-
Play Games

Entity Framework在使用時,很多時間操縱的是Model,並沒有寫sql語句,有時候為了調試或優化等,又需要追蹤Entity framework自動生成的sql(最好還能記錄起來,方便出錯時排查) 方式一: 通過System.Data.Entity.DataBase.Log屬性指定一個無 ...


Entity Framework在使用時,很多時間操縱的是Model,並沒有寫sql語句,有時候為了調試或優化等,又需要追蹤Entity framework自動生成的sql(最好還能記錄起來,方便出錯時排查)

方式一:

通過System.Data.Entity.DataBase.Log屬性指定一個無返回值的委托,來實現記錄日誌的功能

public partial class EFContext<T> : DbContext where T : class
    {
        public EFContext(): base("name=MyConnectionString")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            Database.SetInitializer<EFContext<T>> (null);

            Database.Log = log => File.AppendAllText("ef.log",string.Format("{0}{1}{2}", DateTime.Now, Environment.NewLine, log));

            modelBuilder.Configurations.Add(new MemberMap());
            modelBuilder.Configurations.Add(new RoleMap());
            base.OnModelCreating(modelBuilder);
        }

        
        public DbSet<T> Table { get; set; }

        public IQueryable<T> GetList(Expression<Func<T,bool>> where)
        {
            return this.Table.Where(where);
        }
    }
View Code

其中:Database.Log = log => File.AppendAllText("ef.log",string.Format("{0}{1}{2}", DateTime.Now, Environment.NewLine, log));  設置寫入日誌

控制台代碼:

EFContext<Member> efMemberContext = new EFContext<Member>();
var memberSet = efMemberContext.Set<Member>().Include("Role");

var memberList = memberSet.OrderBy(m => new { m.RoleId, m.Name });
foreach (Member item in memberList)
{
    Console.WriteLine("{0},Role:{1}",item.Name,item.Role.Name);
}
View Code

運行程式後,打開ef.log文件,發現記錄了日誌

 

方式二:自定義一個類,繼承於DbCommandInterceptor,重寫下麵幾個方法

public class EFDbCommandInterceptor : DbCommandInterceptor
    {
        /// <summary>
        /// 計時器
        /// </summary>
        public volatile Stopwatch watch = new Stopwatch();

        public override void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
            base.NonQueryExecuting(command, interceptionContext);
            watch.Restart();
        }

        public override void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
            watch.Stop();
            if (interceptionContext.Exception != null)
            {
                WriteLog(string.Format("Exception:{1} \r\n --> Error executing command: {0}", command.CommandText, interceptionContext.Exception.ToString()));
            }
            else
            {
                WriteLog(string.Format("\r\n執行時間:{0} 毫秒\r\n-->ScalarExecuted.Command:{1}\r\n", watch.ElapsedMilliseconds, command.CommandText));
            }
            base.NonQueryExecuted(command, interceptionContext);
        }

        public override void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
            base.ScalarExecuting(command, interceptionContext);
            watch.Restart();
        }

        public override void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
            watch.Stop();
            if (interceptionContext.Exception != null)
            {
                WriteLog(string.Format("Exception:{1} \r\n --> Error executing command: {0}", command.CommandText, interceptionContext.Exception.ToString()));
            }
            else
            {
                WriteLog(string.Format("\r\n執行時間:{0} 毫秒\r\n-->ScalarExecuted.Command:{1}\r\n", watch.ElapsedMilliseconds, command.CommandText));
            }
            base.ScalarExecuted(command, interceptionContext);
        }

        public override void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
        {
            base.ReaderExecuting(command, interceptionContext);
            watch.Restart();
        }

        public override void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
        {
            watch.Stop();
            if (interceptionContext.Exception != null)
            {
                WriteLog(string.Format("Exception:{1} \r\n --> Error executing command: {0}", command.CommandText, interceptionContext.Exception.ToString()));
            }
            else
            {
                WriteLog(string.Format("\r\n執行時間:{0} 毫秒\r\n-->ScalarExecuted.Command:{1}\r\n", watch.ElapsedMilliseconds, command.CommandText));
            }
            base.ReaderExecuted(command, interceptionContext);
        }
        /// <summary>
        /// 記錄日誌
        /// </summary>
        /// <param name="msg">消息</param>
        private void WriteLog(string msg)
        {
            //指定true表示追加
            using (TextWriter writer = new StreamWriter("Db.log",true))
            {
                writer.WriteLine(msg);   
            }
        }
    }
View Code
public partial class EFContext<T> : DbContext where T : class
    {
        public EFContext(): base("name=MyConnectionString")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            Database.SetInitializer<EFContext<T>> (null);

            //Database.Log = log => File.AppendAllText("ef.log",string.Format("{0}{1}{2}", DateTime.Now, Environment.NewLine, log));

            DbInterception.Add(new EFDbCommandInterceptor());

            modelBuilder.Configurations.Add(new MemberMap());
            modelBuilder.Configurations.Add(new RoleMap());
            base.OnModelCreating(modelBuilder);
        }

        
        public DbSet<T> Table { get; set; }

        public IQueryable<T> GetList(Expression<Func<T,bool>> where)
        {
            return this.Table.Where(where);
        }
    }
View Code

其中DbInterception.Add(new EFDbCommandInterceptor());  設置日誌記錄

還是剛纔的控制台代碼,運行程式,打開Db.log

 

 

另外還有其它方法獲取Entity Framework 執行的sql代碼,比如SQL Server Profiler工具,不過這個不屬於通過Entity Framework代碼去配置,所以在此就不再贅述

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一:函數作為返回值 二:閉包 ...
  • 我們都知道linux下所有設備都是以文件存在的,所以當我們需要用到這些設備的時候,首先就需要打開它們,下麵我們來詳細瞭解一下文件I/O操作。 用到的文件I/O有以下幾個操作:打開文件、讀文件、寫文件、關閉文件等,對應用到的函數有:open、read、write、close、lseek(文件指針偏移) ...
  • cd命令用來切換工作目錄至dirname。 其中dirName表示法可為絕對路徑或相對路徑。若目錄名稱省略,則變換至使用者的home directory(也就是剛login時所在的目錄)。 另外,~也表示為home directory的意思,.則是表示目前所在的目錄,..則表示目前目錄位置的上一層目 ...
  • 1.環境: /home/jello # uname -aLinux 3.10.0 #2 SMP Mon Mar 6 17:52:09 CST 2017 armv7l GNU/Linux 2.獲取mono源碼 wget download.mono-project.com/sources/mono/mo ...
  • 1、概述 log4net是.Net下一個非常優秀的開源日誌記錄組件。log4net記錄日誌的功能非常強大。它可以將日誌分不同的等級,以不同的格式,輸出到不同的媒介。本文主要是介紹如何在Visual Studio2008中使用log4net快速創建系統日誌,如何擴展以輸出自定義欄位。 2、一個簡單的使 ...
  • 在做一個小東西的時候出現了這個問題,就是使用VS調試幾次項目後,使用SQL Server Management Studio管理資料庫時,使用SA登錄就會出現這個錯誤,當然,如果項目中的資料庫連接字元串中使用的sa驗證,那麼項目也會連不到資料庫的.可是如果是在 Server Management S ...
  • 要將一個對象序列化,可是如果對象的屬性為null的時候,我們想將屬性為null的都去掉。 在這裡我使用Newtonsoft.Json.dll 記錄一下序列化以及反序列化 json字元串轉對象 將對象轉化為json格式字元串 那麼如何序列化為json時過濾掉NULL呢?? 直接這樣JsonConver ...
  • 在工作過程中,調用第三方介面出現當返回的數據是中文的時候,中文數據便會變成 這樣??? 迷~ ,一開始我以為是發送成功後接收字元編碼是不是不對,在換過UTF-8,Unicode,。。。都是不行。 最後是問我大佬解決的,希望我大佬帶我飛。 就是解碼用Unicode content-Type 是 app ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...