2
有沒有辦法來確定打開DbContext
當前SQL Server會話ID(@@SPID
),短直接使一個SQL數據庫查詢的?如何從實體框架DbContext收集當前的SQL Server會話ID?
如果有,是否有任何保證SQL Server會話ID將保持不變,直到DbContext
被釋放並且其連接被釋放回實體框架連接池?一些與此類似:
using (MyEntities db = new MyEntities()) {
// the following 3 pieces of code are not existing properties and will result in compilation errors
// I'm just looking for something similar to the following 3 lines
db.CurrentSessionId; //error
db.Database.CurrentSessionId; //error
((IObjectContextAdapter)db).ObjectContext.Connection.CurrentSessionId; //error
// the following code will work, but will this session id be the same until the original DbContext is disposed?
// is there any chance that a db.Database.SqlQuery call will spin off it's own connection from the pool?
short spid = db.Database.SqlQuery<short>("SELECT @@SPID").FirstOrDefault();
}
有趣。我仍然試圖圍繞Entity Framework如何處理連接池的問題進行討論。我的問題從我從與@@ spid的一個表的WebAPI請求作爲主鍵然後通過的EntityFramework上另一個表的次要變化存儲用戶/設備信息這樣的事實。目標是讓該表上的觸發器通過當前@@ spid選擇用戶/設備並存儲有關更改的審計信息。我們發現大約有1/50,000次,@@ spid會在執行這些觸發器時存儲錯誤的用戶/設備信息。 – dvlsg