Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
808 views
in Technique[技术] by (71.8m points)

c# - Entity Framework and transaction isolation level

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.

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 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...