SQL Server Entity framework type of read lock

kgsdhlau  于 2023-04-10  发布在  其他
关注(0)|答案(1)|浏览(112)

What is the default read lock for entity framework and how can i implement the repeatable read lock.

I am thinking that perhaps there is a global settings somewhere so that a readlock is acquired of type repeatable read by default then released once savechanges kicks in.

What is the default transaction isolation level in Entity Framework when I issue “SaveChanges()”? .Says here that the default isolation level is snapshot.How can i change to repeatable read.

fnx2tebb

fnx2tebb1#

Msdn tells default isolation mode is database dependent. (2023 documentation does too, and has much better code examples.)

It also supply an example of how to handle transactions, which is what you need to benefit from what you likely want with isolation mode repeatable read . Beware, their example has a serious flaw, as it will swallow any exception.

Here is a fixed version of their example. context is supposed to be an instance of a class derived from DBContext .

using (var dbContextTransaction =
    context.Database.BeginTransaction(IsolationLevel.RepeatableRead))
{
    try
    {
        // Your work here, then

        context.SaveChanges();
        dbContextTransaction.Commit();
    }
    catch
    {
        dbContextTransaction.Rollback();
        throw;
    }
}

As warned by Panagiotis Kanavos, this kind of locking should be avoided as much as possible. It reduces scalability, increases dead locks risks, may completely blocks other users as long as the transaction is running, ...

The try catch rollback could be considered superfluous, as disposing an ongoing DbTransaction causes it to rollback (and the using will ensures it gets disposed).

相关问题