实体框架事务锁定数据库

时间:2016-06-13 20:30:04

标签: database entity-framework

Db隔离级别设置为ReadCommitted

我是用它做的:

(var trans = _dbContext.Database.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted)) 

但是这仍然会锁定数据库中的表。

在运行另一组执行之前我需要这些值但是我不想在完成所有操作之前将值提交到DB中。

using (var trans = _dbContext.Database.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted))
        {
int value=getNewValue(oldvalue);

int someothervalue=DoSomeOtherAction(value);

//Some more methods same like this 

trans.Commit();
return true;
}
catch
    (Exception e)
        {
          trans.Rollback(); 
          _logger.Error(e);
           throw e;
           return false;
        }

// Here is the GetNewValue Method

Public int getNewValue(int oldvalue)
{
 var job = _dbContext.VALUE_DATA.FirstorDefault(x => x.value == oldvalue);
 var someData = new VALUE_DATA();
 someData.status = job.status;          
 someData.Date = job.Date;
 someData.Source = job.Source;
 someData.Start_DT = job.Start_DT;
 someData.End_DT = job.End_DT;
 someData.Notes = job.Notes;
 _dbContext.Set <VALUE_DATA >().Add(someData);
 _dbContext.SaveChanges();
 return someData.ID;
}

// DoSomeOtherAction Method 

Public int DoSomeOtherAction(int value)
{   
 var job = _dbContext.SOME_TABLE.FirstorDefault(x => x.value == value);
 var someValue = new SOME_TABLE();
 someValue.Name=job.Name;
 someValue.Address=job.Address;
_dbContext.Set <SOME_TABLE >().Add(someValue);
_dbContext.SaveChanges();
 Return someValue.ID;
}

1 个答案:

答案 0 :(得分:0)

只需使用clasic方式解决问题:

var transactionOptions = new System.Transactions.TransactionOptions();

// change the leavel to Read Uncommited
transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;

// Use the TransactionScope!
using (var transactionScope = new System.Transactions.TransactionScope(
    System.Transactions.TransactionScopeOption.Required, 
    transactionOptions)
)

using (var _dbContext= new MyDbContext())
{
    // Do your work here!
    transactionScope.Complete();
}

如果您有其他线程正在更改已使用的表,那么您可能会成为脏读问题!

或者,您可以使用DbCommandInterceptor来定位&#34; NOCHECK&#34;到Sql查询。

相关问题