2011-10-03 107 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(); 
    } 
}