EF-記錄程序自動生成並執行的sql語句日志


在EntityFramework的CodeFirst模式中,我們想將程序自動生成的sql語句和執行過程記錄到日志中,方便以后查看和分析。

在EF的6.x版本中,在DbContext中有一個Database屬性,Database.Log就是用來專門記錄這種日志的。

Database.Log是一個Action<string>委托,給其賦值一個函數就行。

代碼如下:

using Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DAL {
    public class DemoContext:DbContext {
        //使用name=EFDemo的連接字符串
        public DemoContext() : base("EFDemo") {

            //設置數據庫初始化方式 為 遷移(更新)數據庫到最新的版本
            //DemoContext 映射數據庫和表 
            //DAL.Migrations.Configuration 是遷移配置
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<DemoContext, DAL.Migrations.Configuration>());
            
            //將執行的sql語句記錄到日志
            Database.Log = message=>Console.WriteLine("[{0}]{1}-- {2}",Thread.CurrentThread.ManagedThreadId,DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff"),message.Trim());
        }

        //Students屬性對應數據庫中的Student表
        public virtual DbSet<Student> Students { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder) {
            base.OnModelCreating(modelBuilder);
        }
    }
}

應用程序中的代碼如下:

using (DemoContext context = new DemoContext()) {
                //在使用模型類之前需要強制創建數據庫 true:強制創建
                context.Database.Initialize(true);

                #region 新增

                Student stu = new Student {
                    Name = "趙子成",
                    BirthDay = DateTime.Parse("1990-08-01"),
                    Age = 27
                };

                //新增一個Student實體,相當於在Student表中,新增一條數據
                context.Students.Add(stu);              

                //保存
                context.SaveChanges();
              
                #endregion
}

日志記錄的結果如下:

[10]2017/07/29 16:57:28.971-- Opened connection at 2017/07/29 16:57:28 +08:00
[10]2017/07/29 16:57:28.972-- Started transaction at 2017/07/29 16:57:28 +08:00
[10]2017/07/29 16:57:28.977-- DECLARE @generated_keys table([ID] uniqueidentifier)
INSERT [dbo].[Student]([Name], [BirthDay], [Age], [Address])
OUTPUT inserted.[ID] INTO @generated_keys
VALUES (@0, @1, @2, NULL)
SELECT t.[ID], t.[RowVersion]
FROM @generated_keys AS g JOIN [dbo].[Student] AS t ON g.[ID] = t.[ID]
WHERE @@ROWCOUNT > 0
[10]2017/07/29 16:57:28.977--
[10]2017/07/29 16:57:28.978-- -- @0: '趙子成' (Type = String, Size = 50)
[10]2017/07/29 16:57:28.978-- -- @1: '1990/08/01 00:00:00' (Type = DateTime2)
[10]2017/07/29 16:57:28.978-- -- @2: '27' (Type = Int32)
[10]2017/07/29 16:57:28.978-- -- Executing at 2017/07/29 16:57:28 +08:00
[10]2017/07/29 16:57:28.993-- -- Completed in 14 ms with result: SqlDataReader
[10]2017/07/29 16:57:28.993--
[10]2017/07/29 16:57:28.995-- Committed transaction at 2017/07/29 16:57:28 +08:00
[10]2017/07/29 16:57:28.996-- Closed connection at 2017/07/29 16:57:28 +08:00

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM