2011-10-03 57 views
4

我所要做的主要是what NHibernate does當你做這樣的事情:實體框架 - 悲觀鎖定

var instance = session.Get<Customer>(id, LockMode.Upgrade); 

我需要鎖定的實體排在數據庫中。爲什麼我需要這個? 想象一下,可以同時由多個參與者(人員或流程)更新的工作流實例。

我的約束不允許樂觀鎖定解決方案。

回答

6

EF不支持此操作。如果您想查詢鎖定一些記錄必須做這樣的事情:

using (var scope = new TransactionScope(...)) 
{ 
    using (var context = new YourContext(...)) 
    { 
     var customer = 
      context.ExecuteStoreQuery<Customer>("SELECT ... FROM Customers WITH (UPDLOCK) WHERE ..."); 

     // rest of your logic while record is locked 

     scope.Complete(); 
    } 
} 

或者context.Database.SqlQuery中的DbContext API的情況下。

1

你也可以將你的SQL代碼EDMX存儲模型,如果你不想在你的C#代碼普通的SQL(見here):

<Function Name="LockTestTable" IsComposable="false"> 
    <CommandText> 
     SELECT NULL 
     FROM TestTable WITH (UPDLOCK) 
     WHERE TestTableID = @testTableID 
    </CommandText> 
    <Parameter Name="testTableID" 
     Mode="In" 
     Type="int" /> 
</Function> 

,並調用它像這樣

using (var scope = new TransactionScope(...)) 
{ 
    using (var context = new YourContext(...)) 
    { 
     context.LockTestTable(1); 

     // Record locked 

     scope.Complete(); 
    } 
}