Welcome

首页 / 软件开发 / .NET编程技术 / ADO.NET Entity Framework深入分析,Part 6–处理并发(Concurrency Handling)

ADO.NET Entity Framework深入分析,Part 6–处理并发(Concurrency Handling)2010-09-10EntLib设置并发模式

Entity Framework 实现了乐观的并发模式(Optimistic Concurrency Model)。默认情况下,在实体更新数据提交到数据库时,并不会检查并发。对于高频率的并发属性,你需要设置属性的并发模式为Fixed。

这些属性将会加入到T-SQL脚本的WHERE子句部分,用来比较客户端的值和数据库端的值。

示例代码:

public void UpdateProduct()
{
Product product = context.Product.FirstOrDefault(p => p.ProductID == 1004);
if (product != null)
{
product.Color = "White";
product.StandardCost = 200;
product.ListPrice = 250;
}
context.SaveChanges();
}

正常情况下,不检查并发情况,产生的T-SQL脚本如下:

exec sp_executesql N"update [SalesLT].[Product]
set [Color] = @0, [StandardCost] = @1, [ListPrice] = @2
where ([ProductID] = @3)",
N"@0 nvarchar(5), @1 decimal(19,4), @2 decimal(19,4), @3 int", @0=N"White", @1=1000.0000, @2=2000.0000,@3=1004

在设置Product实体的Color属性的Concurrency Mode 为Fixed,你会发现生成的T-SQL脚本中,Where子句中增加了对Color 字段的检查:

exec sp_executesql N"update [SalesLT].[Product]
set [Color] = @0, [StandardCost] = @1, [ListPrice] = @2
where (([ProductID] = @3) and ([Color] = @4))",
N"@0 nvarchar(5), @1 decimal(19,4), @2 decimal(19,4), @3 int, @4 nvarchar(5)", @0=N"White", @1=200.0000, @2=250.0000, @3=1004, @4=N"White"