使用EntityFramework查詢資料庫,SSMS的Activity Monitor出現3個同Session的資料

  • 273
  • 0
  • 2016-12-02

使用EntityFramework查詢資料庫,SSMS的Activity Monitor出現3個同Session的資料!?

在做某一專案中時,因為專案是使用EntityFramework查詢MS資料庫。

有一天同事問說,平常觀看SSMS的活動監視器(Activity Monitor)都可以看得出每個查詢的處理序。

沒有使用Entity Framework(以下簡稱EF)的應用程式,大部分都是使用SqlConnection物件,與資料庫溝通,所以從活動監視器最常看到的就是下圖這樣

(圖一)

只有一個,應用程式的確是使用.NET SqlClient的方式來取得資料。

另外也可以使用下面的語法取得

SELECT   
    c.session_id, c.net_transport, c.encrypt_option,   
    c.auth_scheme, s.host_name, s.program_name,   
    s.client_interface_name, 
     c.connect_time,   
    s.login_time   
FROM sys.dm_exec_connections AS c  
JOIN sys.dm_exec_sessions AS s  
    ON c.session_id = s.session_id   

 

結果如下:(圖二)

接著我們使用EF的方式取得資料

結果~在活動監視器出現了3個一樣的Session(圖三)

資料都一模一樣阿~~~看不出來有何差異,後來一樣用Sql語法直接查看

原來雖然在sys.dm_exec_sessions只有一個,但是sys.dm_exec_connections有出現3個相同的Session

因為活動監視器也是使用sys.dm_exec_sessions Join到sys.dm_exec_connections,所以就跑出3個了

(圖四)

至於為甚麼出現3個,主要原因是因為在設定EF的ConnectionString中,MultipleActiveResultSets(MARS)被設為True,所以才出現多個。

MultipleActiveResultSets(又簡稱MARS):允許在單一連接中執行多個批次作業的功能。

可以參考下列文章

ASP.NET 中 MARS(多重作用結果集)

淺談多重作用結果集(Multiple Active Result Set,MARS)

如果MARS設為False,在活動監視器中,就變成只會出現一筆。

不過設定為True或是False要再特別注意喔~~特別是使用EF的朋友,設定成False會出現很多意想不到的錯誤.......

 

 

參考資料:

 

 

創用 CC 授權條款
本著作由Chenting Weng製作,以創用CC 姓名標示 4.0 國際 授權條款釋出。
This work by Chenting Weng is licensed under a Creative Commons Attribution 4.0 International License.
Based on a work at https://dotblogs.com.tw/chentingw.

部分文章內容會引用到其他網站的簡介或圖片,若有侵犯到您的著作權,請留言告知,本人會儘快移除。
免責聲明:文章屬個人記事使用,僅供參考,若引用文章造成一切損失,本人不承擔任何責任。如有錯誤,歡迎留言告知。

Part of the content of the article will refer to the profile or picture of other websites.
If there is any infringement of your copyright, please leave a message and let me remove it as soon as possible.
Disclaimer:The article is for personal use and is for reference only. I will not bear any responsibility for any loss caused by quoting the article. If there is an error, please leave a message to inform.