2014-02-19 14 views
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(); 
} 

回答

1

首先,單單的DbContext將打開數據庫的任何SQL過程。查詢確實是

所以在這種情況下,當你運行SELECT @@SPID你一定會打開一個新的工藝與新的ID。

好消息是的EntityFramework將使用相同的進程來運行後續查詢。理想情況下,在相同的使用塊中,您將始終獲得相同的@@ SPID值。

您可以運行此查詢

select * 
from master.dbo.sysprocesses 
where program_name = 'EntityFramework' 

觀察與實體框架相關的數據庫的當前進程。

然後,您可以使用下面的查詢來獲取與特定的進程相關聯的SQL語句。欲瞭解更多信息,請看看這裏接受的答案:List the queries running on SQL Server

declare 
    @spid int 
, @stmt_start int 
, @stmt_end int 
, @sql_handle binary(20) 

set @spid = XXX -- Fill this in 

select top 1 
    @sql_handle = sql_handle 
, @stmt_start = case stmt_start when 0 then 0 else stmt_start/2 end 
, @stmt_end = case stmt_end when -1 then -1 else stmt_end/2 end 
from master.dbo.sysprocesses 
where spid = @spid 
order by ecid 

SELECT 
    SUBSTRING( text, 
      COALESCE(NULLIF(@stmt_start, 0), 1), 
      CASE @stmt_end 
       WHEN -1 
        THEN DATALENGTH(text) 
       ELSE 
        (@stmt_end - @stmt_start) 
       END 
     ) 
FROM ::fn_get_sql(@sql_handle) 
+0

有趣。我仍然試圖圍繞Entity Framework如何處理連接池的問題進行討論。我的問題從我從與@@ spid的一個表的WebAPI請求作爲主鍵然後通過的EntityFramework上另一個表的次要變化存儲用戶/設備信息這樣的事實。目標是讓該表上的觸發器通過當前@@ spid選擇用戶/設備並存儲有關更改的審計信息。我們發現大約有1/50,000次,@@ spid會在執行這些觸發器時存儲錯誤的用戶/設備信息。 – dvlsg