在实体框架默认的事务隔离级别是什么,当我发出“调用SaveChanges()”?当我、实体、框架、级别

2023-09-02 12:02:51 作者:梦已逝あ莫相思

在实体框架默认的事务隔离级别是什么,当我发出调用SaveChanges()?我找不到它的任何地方。应被序列化?

What is the default transaction isolation level in Entity Framework when I issue "SaveChanges()"? I can not find it anywhere. Shall it be "Serializable"?

推荐答案

的SaveChanges 使用实施 DbTransaction 当前存储供应商。这意味着,默认事务隔离级别被设为默认值的数据库服务器。在SQL Server是提交读。如果你想改变隔离级别,您可以使用的TransactionScope 。您也可以覆盖的SaveChanges 在派生背景下,敷 base.SaveChanges()来直接在覆盖方法的范围。

SaveChanges uses implementation of DbTransaction for current store provider. It means that default transaction isolation level is set to default value for the database server. In SQL Server it is READ COMMITTED. If you want to change isolation level you can use TransactionScope. You can also override SaveChanges in your derived context and wrap base.SaveChanges() to the scope directly in overriden method.

public override void SaveChanges()
{
    // Default isolation level for TransactionScope is Serializable
    using (var scope = new TransactionScope())
    {
        base.SaveChanges();
        scope.Complete();
    }
}

您可以进一步提高这一code,让你通过隔离级别的SaveChanges 等,一旦你开始改变隔离级别,你应该这样做一致。这意味着你应该要运行一个事务,因为隔离级别为每个连接配置和连接复用,每次定义隔离级别在使用连接池。

You can further improve this code to allow you passing isolation level to SaveChanges etc. Once you start changing isolation levels you should do it consistently. It means you should define isolation level each time you want to run a transaction because isolation level is configured per connection and connections are reused when using connection pooling.

编辑:在EF6默认事务级别更改为 READ COMMITTED快照

Default transaction level in EF6 has changed to READ COMMITTED SNAPSHOT