2016-10-18 33 views
0

我想在SQL Server中將表鎖定一段給定的時間。我在代碼級使用C#。我該如何實現它,我還需要驗證表是否被鎖定。我不太瞭解SQL Server中的鎖定表。我想用實體框架來實現它。任何幫助深表感謝。鎖定一個給定時間的SQL服務器表並檢查它是否被鎖定

+1

http://stackoverflow.com/questions/25273157/t-sql-lock-a-table-manually-一分鐘 – Vincent

+1

它不能用純粹的實體框架來完成。你會**有**來使用道。 –

回答

1

您可以嘗試如下所示。

using (var context = new YourContext()) 
    { 
    using (var dbContextTransaction = context.Database.BeginTransaction()) 
    { 
     //Lock the table during this transaction 
     context.Database.ExecuteSqlCommand("SELECT 1 FROM YourTable WITH (TABLOCKX) 
    WAITFOR DELAY '00:03:00'"); 

      //your work here 

      dbContextTransaction.Commit(); 
     } 
} 

注:表鎖後,將被釋放退出BeginTransaction

+1

小編輯。我應該用'dbContextTransaction.Commit()'而不是'scope.Commit()'和SQL命令中的表來替換爲實際表名 –

+1

感謝您的更正。我編輯過:) – Sampath