实体框架和事务隔离级别 [英] Entity Framework and transaction isolation level

查看:161
本文介绍了实体框架和事务隔离级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用实体框架4.0。现在我需要限制访问的表,而我从读,或写它。也许这是有关事务隔离级别。

I'm using Entity Framework 4.0. Now I need to restrict access to a table while I'm reading from it or writing to it. Probably that's about transaction isolation level.

我该怎么办呢?

更新

下面是我

using (var db = new MyDb())
{
    using (TransactionScope scope = new TransactionScope())
    {
        var item = db.MyItems.Single(x => x.Id == 5);
        item.Price = 12;
        db.SaveChanges();
        scope.Complete(); 
    }
}

不过,当我把一个断点放在任意行使用(TransactionScope的范围键,当我停止那里,然后我去到SQL Server Management Studio中,做一个从被一个事务中使用,我没有得到某种原因的错误选择表中查询(甚至更新!)。但是,为什么?它不能让我看在事务正在执行一个数据。

However, when I put a breakpoint at any line inside using (TransactionScope scope and when I'm stopping there and then I go to Sql Server Management Studio and doing a select query (or even update!) from a table that is using inside a transaction, I'm not getting an error for some reason. But why? It must not allow me to read a data while a transaction is executing.

推荐答案

在默认情况下一个事务都有一个<一个href="http://msdn.microsoft.com/en-us/library/system.transactions.isolationlevel.aspx">IsolationLevel的序列化。序列化是最高级别。它要求的任何其它交易被允许对数据进行操作之前的事务完成

By default a Transaction has an IsolationLevel of Serializable. Serializable is the highest level. It requires that the transaction completes before any other transaction is allowed to operate on the data.

它具有以下限制:

  • 语句不能读取已修改的数据,但尚未 犯下的其他交易。
  • 在没有其它事务可以修改 已读出的当前事务,直到当前数据 交易完成。
  • 在其他事务不能插入新行 关键值将下降键,任何读取范围 直至当前事务在当前事务中的语句 完成。
  • Statements cannot read data that has been modified but not yet committed by other transactions.
  • No other transactions can modify data that has been read by the current transaction until the current transaction completes.
  • Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes.

这是一个伟大的博客文章,介绍如何使用交易与实体框架: Entity Framework的事务范围的例子

This is a great blog post that explains how to use Transactions with the Entity Framework: Entity Framework transaction scope examples

在实体框架6默认的IsolationLevel更改为READ_COMMITTED_SNAPSHOT使用code首先创建的数据库,可能允许更多的可扩展性和更少的deadlocks.See中的 EF 6对codePLEX 未来规范

In Entity Framework 6 the default IsolationLevel is changed to READ_COMMITTED_SNAPSHOT for databases created using Code First, potentially allowing for more scalability and fewer deadlocks.See the future spec of EF 6 on codeplex

这篇关于实体框架和事务隔离级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆