Ado.net Entity Framework In-depth analysis, part 6– processing concurrency (concurrency handling)

Source: Internet
Author: User

Set concurrency mode

The Entity Framework implements an optimistic concurrency pattern (optimistic concurrency model). By default, concurrency is not checked when entity update data is submitted to the database. For high frequency concurrency properties, you need to set the concurrency mode of the property to fixed.

These properties are added to the WHERE clause section of the T-SQL script to compare the client's values with the values on the database side.

Sample code:

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();
}

Normally, without checking concurrency, the resulting T-SQL script is as follows:

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

When you set the concurrency Mode for the color property of the product entity to fixed, you will find that in the generated T-SQL script, the WHERE clause adds a check to the Color field:

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'

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.