C# 实体框架和事务隔离级别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12795184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Entity Framework and transaction isolation level
提问by Alan Coromano
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.
我正在使用实体框架 4.0。现在,我需要在读取表或写入表时限制对表的访问。可能这与事务隔离级别有关。
How do I do that?
我怎么做?
Update
更新
here is what I have
这是我所拥有的
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();
}
}
However, when I put a breakpoint at any line inside using (TransactionScope scopeand 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.
但是,当我在里面的任何行上放置一个断点using (TransactionScope scope并在那里停下来然后我转到 Sql Server Management Studio 并从事务中使用的表中执行选择查询(甚至更新!)时,我由于某种原因,我没有收到错误消息。但为什么?它不允许我在事务执行时读取数据。
采纳答案by Wouter de Kort
By default, a Transaction has an IsolationLevelof Serializable. Serializable is the highest level. It requires that the transaction completes before any other transaction is allowed to operate on the data.
默认情况下,事务的IsolationLevel为 Serializable。可序列化是最高级别。它要求在允许任何其他事务对数据进行操作之前完成事务。
It has the following restrictions:
它有以下限制:
- 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.
- 语句无法读取已被其他事务修改但尚未提交的数据。
- 在当前事务完成之前,没有其他事务可以修改当前事务已读取的数据。
- 在当前事务完成之前,其他事务不能插入键值落在当前事务中任何语句读取的键范围内的新行。
This is a great blog post that explains how to use Transactions with the Entity Framework: Entity Framework transaction scope examples
这是一篇很棒的博客文章,解释了如何在实体框架中使用事务:实体框架事务范围示例
UPDATE
更新
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
在 Entity Framework 6 中,对于使用 Code First 创建的数据库,默认 IsolationLevel 更改为 READ_COMMITTED_SNAPSHOT,这可能允许更高的可伸缩性和更少的死锁。查看EF 6的未来规格

