我有一些.NET代码包含在可重复读取事务中,代码如下:
using (
var transaction = new TransactionScope(
TransactionScopeOption.Required,
new TransactionOptions { IsolationLevel = IsolationLevel.RepeatableRead },
TransactionScopeAsyncFlowOption.Enabled))
{
int theNextValue = GetNextValueFromTheDatabase();
var entity = new MyEntity
{
Id = Guid.NewGuid(),
PropertyOne = theNextValue, //An identity column
PropertyTwo = Convert.ToString(theNextValue),
PropertyThree = theNextValue,
...
};
DbSet<MyEntity> myDbSet = GetEntitySet();
myDbSet.Add(entity);
await this.databaseContext.Entities.SaveChangesAsync();
transaction.Complete();
}
第一种方法
GetNextValueFromTheDatabase
,从数据库中的表中检索存储在列中的最大值。我使用可重复读取,因为我不希望两个用户读取并使用相同的值。然后,我只需在内存中创建一个实体Entity
并调用SaveChangesAsync()
将值写入数据库。偶尔,我会发现实体.PropertyOne、实体.PropertyTwo和实体.PropertyThree的值不匹配。例如,实体.PropertyOne的值为500,但实体.PropertyTwo和实体.PropertyThree的值为499。这是怎么可能的?即使代码没有包含在事务中,我也希望这些值匹配(如果两个用户同时运行,则可能在实体中重复)。
我正在使用Entity Framework 6和Sql Server 2008R2。 编辑:
以下是
GetNextValueFromTheDatabase
的代码:public async Task<int> GetNextValueFromTheDatabase()
{
return await myQuerable
.OrderByDescending(x => x.PropertyOne) //PropertyOne is an identity column (surprise!)
.Select(x => x.PropertyOne)
.Take(1)
.SingleAsync() + 1;
}