Entity Framework Tutorial Basics(28):Concurrency
Concurrency in Entity Framework:
Entity Framework supports Optimistic Concurrency by default. In the optimistic concurrency, EF saves the entity to the database, assuming that the same data has not changed since the entity was loaded. If it determines that the data has changed, then an exception is thrown and you must resolve the conflict before attempting to save it again.
Let's see how to handle optimistic concurrency with Student entity.
First of all, you need to have a rowversion column in the Student table in order to handle concurrency with Student entity. Rowversion is a datatype in the SQL Server that automatically generates unique binary number whenever the insert or update operation is performed in a table. The rowversion datatype is simply an incrementing number. Rowversion is a similar to the timestamp datatype.
Create a new column RowVersion in Student table with timestamp datatype as shown below:
Note: The value of RowVersion will be added and updated automatically by the database during the Insert and Update operation.
Now, create a new Entity Data Model as shown in Create Entity Data Model section or if you already have an EDM then update it by right clicking on designer -> Update Model From Database -> Refresh Student table. Now, you will see the RowVersion property added in the Student entity.
Then, you need to set the concurrency mode to fixed by right clicking on RowVersion property in the Student entity (right click on RowVersion property not Student entity) -> select Property. Change Concurrency Mode to Fixed from None in the property window as shown below:
EF will now include a RowVersion column in the where clause, whenever you do an update operation and if the rowversion value is different than in the where clause then it will throwDbUpdateConcurrencyException.
The following code shows that User1 and User2 get the same student and update StudentName at the same time:
Student student1WithUser1 = null;
Student student1WithUser2 = null; //User 1 gets student
using (var context = new SchoolDBEntities())
{
context.Configuration.ProxyCreationEnabled = false;
student1WithUser1 = context.Students.Where(s => s.StudentID == ).Single();
}
//User 2 also get the same student
using (var context = new SchoolDBEntities())
{
context.Configuration.ProxyCreationEnabled = false;
student1WithUser2 = context.Students.Where(s => s.StudentID == ).Single();
}
//User 1 updates Student name
student1WithUser1.StudentName = "Edited from user1"; //User 2 updates Student name
student1WithUser2.StudentName = "Edited from user2";
User1 saves his changes before User2. So when user2 tries to save the changes, he will get concurrency exection:
//User 1 saves changes first
using (var context = new SchoolDBEntities())
{
try
{
context.Entry(student1WithUser1).State = EntityState.Modified;
context.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
Console.WriteLine("Optimistic Concurrency exception occured");
}
} //User 2 saves changes after User 1.
//User 2 will get concurrency exection
//because CreateOrModifiedDate is different in the database
using (var context = new SchoolDBEntities())
{
try
{
context.Entry(student1WithUser2).State = EntityState.Modified;
context.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
Console.WriteLine("Optimistic Concurrency exception occured");
}
}
Concurrency in Code-First:
You can create a timestamp property in code-first by using [Timestamp] attribute. Make sure that the property type is byte[] because timestamp is binary in C#.
[Timestamp]
public byte[] RowVersion { get; set; }
EF includes a property in the where clause, during the update operation, if the property is marked with the Timestamp attribute.
You can resolve concurrency exceptions many ways. Visit msdn for detailed information on how to resolve optimistic concurrency.
Download sample project for the basic tutorials.
Entity Framework Tutorial Basics(28):Concurrency的更多相关文章
- Entity Framework Tutorial Basics(1):Introduction
以下系列文章为Entity Framework Turial Basics系列 http://www.entityframeworktutorial.net/EntityFramework5/enti ...
- Entity Framework Tutorial Basics(4):Setup Entity Framework Environment
Setup Entity Framework Environment: Entity Framework 5.0 API was distributed in two places, in NuGet ...
- Entity Framework Tutorial Basics(43):Download Sample Project
Download Sample Project: Download sample project for basic Entity Framework tutorials. Sample projec ...
- Entity Framework Tutorial Basics(42):Colored Entity
Colored Entity in Entity Framework 5.0 You can change the color of an entity in the designer so that ...
- Entity Framework Tutorial Basics(41):Multiple Diagrams
Multiple Diagrams in Entity Framework 5.0 Visual Studio 2012 provides a facility to split the design ...
- Entity Framework Tutorial Basics(37):Lazy Loading
Lazy Loading: One of the important functions of Entity Framework is lazy loading. Lazy loading means ...
- Entity Framework Tutorial Basics(36):Eager Loading
Eager Loading: Eager loading is the process whereby a query for one type of entity also loads relate ...
- Entity Framework Tutorial Basics(34):Table-Valued Function
Table-Valued Function in Entity Framework 5.0 Entity Framework 5.0 supports Table-valued functions o ...
- Entity Framework Tutorial Basics(33):Spatial Data type support in Entity Framework 5.0
Spatial Data type support in Entity Framework 5.0 MS SQL Server 2008 introduced two spatial data typ ...
随机推荐
- New Concept English three (53)
30w/m 56errors The Scandinavian countries are much admired all over the world for their enlightened ...
- translation exercise 3
The high-resolution photograph was taken with a 135-mm lens mounted on a digital SLR camera.这张高清照片是用 ...
- freemarker实现第一个HelloWorld
第一步:引入freemarker jar包 第二步:创建templates下的test01.ftl 第三步:在web.xml下 第四步:编写后台代码 package com.wisezone.test ...
- 461. Hamming Distance Add to List
// 快速法求1的个数 int BitCount2(unsigned int n) { unsigned ; ; n; ++c) { n &= (n -) ; // 清除最低位的1 } ret ...
- [Unity3D]关于U3D贴图格式压缩
http://blog.sina.com.cn/s/blog_5b6cb9500102vi6i.html 因为有不少人都问过我压缩格式的问题,今天飞哥又重新提醒了一次.整理一下发个贴,以供大家查阅和讨 ...
- zabbix监控进程
参考http://chenx1242.blog.51cto.com/10430133/1837990 1 前期说明 zabbix_server查看“文件在后台运行数量”所对应的key就是:proc.n ...
- 利用PowerDesigner设计数据库
PowerDesigner非常强大, 可以利用它完成数据库的设计. 1.下载地址:http://pan.baidu.com/s/1DsLrg 2.表设计: 建立概念数据模型(Conceptual Da ...
- flask之python3 虚拟环境及使用dotnv来永久保存环境变量
Python 3 comes bundled with the venv module to create virtual environments Create an environment Cre ...
- Mockito为什么不能mock静态方法
因为Mockito使用继承的方式实现mock的,用CGLIB生成mock对象代替真实的对象进行执行,为了mock实例的方法,你可以在subclass中覆盖它,而static方法是不能被子类覆盖的,所以 ...
- 【转】Jquery修改image的src属性,图片不加载问题
1.当点击某一按钮的时候,把图片域中的图片改变一下 <img id="randimg" src="/servlet/CreateValidateNum&quo ...