1. 程式人生 > >監視EntityFramework中的sql流轉你需要知道的三種方式Log,SqlServerProfile, EFProfile

監視EntityFramework中的sql流轉你需要知道的三種方式Log,SqlServerProfile, EFProfile

div tex 安裝 all pan generated form int info

大家在學習entityframework的時候,都知道那linq寫的叫一個爽,再也不用區分不同RDMS的sql版本差異了,但是呢,高效率帶來了差靈活性,我們

無法控制sql的生成策略,所以必須不要讓自己缺乏好的工具去監控sql,本篇給大家介紹的三種監控手段Log和SqlServer profile,ef profile。。。

一:Log監控

  這個屬於entity framework自帶的一個Action方法,它給大家帶來了不錯的用戶體驗,我們可以將其輸出放到控制臺,又或者寫入到記事本中。。。這

裏我就通過EDM來生成codefirst,可以看到如下的Database的Log定義,然後大家就可以給他灌入一個帶string參數的Action方法,比如Console.WriteLine。

技術分享圖片
 //
        // 摘要:
        //     Set this property to log the SQL generated by the System.Data.Entity.DbContext
        //     to the given delegate. For example, to log to the console, set this property
        //     to System.Console.Write(System.String).
        //
        // 備註:
        //     The format of the log text can be changed by creating a new formatter that derives
        //     from System.Data.Entity.Infrastructure.Interception.DatabaseLogFormatter and
        //     setting it with System.Data.Entity.DbConfiguration.SetDatabaseLogFormatter(System.Func{System.Data.Entity.DbContext,System.Action{System.String},System.Data.Entity.Infrastructure.Interception.DatabaseLogFormatter}).
        //     For more low-level control over logging/interception see System.Data.Entity.Infrastructure.Interception.IDbCommandInterceptor
        //     and System.Data.Entity.Infrastructure.Interception.DbInterception.
        public Action<string> Log { get; set; }
技術分享圖片 技術分享圖片
 1     static void Main(string[] args)
 2         {
 3             using (SchoolDB2Entities dbContext = new SchoolDB2Entities())
 4             {
 5                 dbContext.Database.Log = Console.WriteLine;
 6 
 7                 dbContext.Students.Add(new Student()
 8                 {
 9                     StudentName = "jack123"
10                 });
11 
12                 dbContext.SaveChanges();
13             }
14         }
技術分享圖片

技術分享圖片

由於codefirst初始化生成之時內容太多,無法一一顯示出來。。。為了方便可灌入自定義方法AppendLog,比如將其灌入到File中。。。

技術分享圖片

二:SqlServer Profile

可以看到SqlServer Profile是放在sqlserver層面上的監控,可以監控到各種sql如何流入到sqlserver中,但是如果你默認開啟的話,會看到很多與

ef無關的操作,比如下面這樣:

技術分享圖片

那更好的方式是怎麽過濾呢? 其實也很簡單,我們只需要在ef的connectionstring中塞入一個App標記,然後在sqlserver profile上面進行篩選就可以了。

第一步:在connectionstring中加入applicationName

  <connectionStrings>
    <add name="SchoolDB2Entities" connectionString="data source=.;initial catalog=SchoolDB2;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
  </connectionStrings>

第二步:在SqlProfile中篩選ApplicationName=EntityFramework的所有記錄

技術分享圖片

ok,這樣我們就配置好了,接下來我們將codefirst跑起來,可以清清楚楚的看到,現在的profile中僅僅只有EntityFramework標記生成的sql語句了。

技術分享圖片

三:Entity Framework Profile

首先這個是一款商業軟件,免費試用期是30天,不過網上還是能夠搜索到各種破解版,廢話不多說,我們通過nuget下載一下:

技術分享圖片

技術分享圖片
PM> Install-Package EntityFrameworkProfiler
正在嘗試收集與目標為“.NETFramework,Version=v4.6”的項目“ConsoleApplication37”有關的程序包“EntityFrameworkProfiler.3.0.3103”的相關依賴項信息
正在嘗試解析程序包“EntityFrameworkProfiler.3.0.3103”的依賴項,DependencyBehavior 為“Lowest”
正在解析操作以安裝程序包“EntityFrameworkProfiler.3.0.3103”
已解析操作以安裝程序包“EntityFrameworkProfiler.3.0.3103”
正在將程序包“Microsoft.Web.Infrastructure.1.0.0”添加到文件夾“c:\users\xchuang\documents\visual studio 2015\Projects\ConsoleApplication37\packages”
已將程序包“Microsoft.Web.Infrastructure.1.0.0”添加到文件夾“c:\users\xchuang\documents\visual studio 2015\Projects\ConsoleApplication37\packages”
已將程序包“Microsoft.Web.Infrastructure.1.0.0”添加到“packages.config”
已將“Microsoft.Web.Infrastructure 1.0.0.0”成功安裝到 ConsoleApplication37
正在將程序包“WebActivatorEx.2.0.5”添加到文件夾“c:\users\xchuang\documents\visual studio 2015\Projects\ConsoleApplication37\packages”
已將程序包“WebActivatorEx.2.0.5”添加到文件夾“c:\users\xchuang\documents\visual studio 2015\Projects\ConsoleApplication37\packages”
已將程序包“WebActivatorEx.2.0.5”添加到“packages.config”
已將“WebActivatorEx 2.0.5”成功安裝到 ConsoleApplication37
正在將程序包“EntityFrameworkProfiler.3.0.3103”添加到文件夾“c:\users\xchuang\documents\visual studio 2015\Projects\ConsoleApplication37\packages”
已將程序包“EntityFrameworkProfiler.3.0.3103”添加到文件夾“c:\users\xchuang\documents\visual studio 2015\Projects\ConsoleApplication37\packages”
已將程序包“EntityFrameworkProfiler.3.0.3103”添加到“packages.config”
正在執行腳本文件“c:\users\xchuang\documents\visual studio 2015\Projects\ConsoleApplication37\packages\EntityFrameworkProfiler.3.0.3103.0\tools\Install.ps1”
已將“EntityFrameworkProfiler 3.0.3103.0”成功安裝到 ConsoleApplication37
PM> 
技術分享圖片

下載完之後,再看一下packages文件夾中的子文件夾EntityFrameworkProfiler.3.0.3103.0,找到一個叫做efprof.exe的程序,這個就是要開啟的監控。

技術分享圖片

打開軟件後,大家可以自己註冊一下,生成一個licence的xml,然後大家就可以看到這樣的一個牛逼的界面了。。。。

技術分享圖片

更加牛逼的是,會在我們的Main函數中註入一段開啟邏輯,並且在App_Start中生成了一個cs,一個vb文件,如下:

技術分享圖片
 1     class Program
 2     {
 3         static void Main(string[] args)
 4         {App_Start.EntityFrameworkProfilerBootstrapper.PreStart();
 5 
 6             using (SchoolDB2Entities dbContext = new SchoolDB2Entities())
 7             {
 8                 dbContext.Database.Log = AppendLog;
 9 
10                 dbContext.Students.Add(new Student()
11                 {
12                     StudentName = "jack123"
13                 });
14 
15                 dbContext.SaveChanges();
16             }
17         }
18 
19         static void AppendLog(string str) => System.IO.File.AppendAllText(Environment.CurrentDirectory + "\\1.txt", str, Encoding.Default);
20     }
技術分享圖片

技術分享圖片

既然代碼都生成好了。。。那就留給我要做的事情就是Ctrl + F5了。

技術分享圖片

可以看到,efprofile可以抓拍到各種create table語句,包括各種面板信息: Application Statistics,Analysis,Duration等等。。。最重要的我們還能看到

“Query plan”,比如下面我構造一個相對比較復雜的sql語句:

技術分享圖片
 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             App_Start.EntityFrameworkProfilerBootstrapper.PreStart();
 6 
 7             using (SchoolDB2Entities dbContext = new SchoolDB2Entities())
 8             {
 9                 var query = (from n in dbContext.Students
10                              from m in dbContext.StudentAddresses
11                              where n.StudentID == m.StudentID
12                              group n.StudentID by n.StudentName into g
13                              select new { g.Key, count = g.Count() }).ToList();
14 
15                 dbContext.SaveChanges();
16             }
17         }
18     }
技術分享圖片

然後執行一下,看看efprofile監視到db中是如何生成query plan的快照的。。。

技術分享圖片

好了,三種方式基本上就是這樣了,現在的您是不是會監視自己ef中的sql流轉了呢?

監視EntityFramework中的sql流轉你需要知道的三種方式Log,SqlServerProfile, EFProfile