Entity Framework - pessimistic locking

假装没事ソ 提交于 2019-12-22 08:46:45

问题


What I am trying to do is basically what NHibernate does when you do something like:

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

I need to lock the entity row in the database. Why I need that? Imagine something like a workflow instance that can be updated by multiple actors(people or processes) at the same time.

The constraints I have don't allow for optimistic locking solutions.


回答1:


EF doesn't have support for this. If you want to lock some record by query you must do something like:

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();
    }
}

Or context.Database.SqlQuery in case of DbContext API.




回答2:


You could also move your SQL Code to EDMX storage model, if you don't want to have plain SQL in your C# Code (see 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>

And call it like this

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

        // Record locked

        scope.Complete();
    }
}


来源:https://stackoverflow.com/questions/7635216/entity-framework-pessimistic-locking

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!