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 ...
随机推荐
- C++之结构体struct
原创博客,转载请注明出处! 1.简介 # C++提供一些基本的数据类型(int,float,double,char等),但由于程序处理的问题通常较复杂,基本的数据类型不能满足程序需要,因此C++允许用 ...
- Java垃圾回收机制——finallize()
其实了解JAVA的人,都知道JAVA的GC机制是其的一大优点,它令程序员不需要主动去考虑内存溢出和垃圾回收的问题,不像c++具有显式的析构函数对整个对象进行内存清理以及需要调用delete才可以进行显 ...
- 寻找数组中第K大数
1.寻找数组中的第二大数 using System; using System.Collections.Generic; using System.Linq; using System.Text; u ...
- 使用sort&awk实现文件内容块排序
源文件为: [root@luo5 wangxx]# cat -v luo.txt J LuoSoutth jfsaNanjing,china Y ZhangVictory UniversityNejf ...
- Unity5-ABSystem(五):AssetBundle内存
http://blog.csdn.net/lodypig/article/details/51879702 AssetBundle内存占用 建议 实测 www加载实测 LoadFromFile加载实测 ...
- C#关闭一个窗口的同时打开另一个窗口
在.net的WinForm程序中,如果是直接起动的Form作为主窗口,那么这个主窗口是不能关闭的,因为它维护了一个Windows消息循环,它一旦关闭了就等于声明整个应用程序结束,所以新打开的窗口也就被 ...
- 学习动态性能表(18)--v$system_event
学习动态性能表 第18篇--V$SYSTEM_EVENT 2007.6.13 本视图概括了实例各项事件的等待信息.v$session_wait显示了系统的当前等待项,v$system_event则提 ...
- vc++2008 采用GSoap访问 WebService
(转http://www.cppblog.com/yeqing/articles/12762.html) 前一阶段写gSOAP 的文章没保存好,后来想写的,越学越没有写的勇气了,感觉自己很菜,但是现在 ...
- 洛谷【P1439】【模板】最长公共上升子序列
浅谈\(DP\):https://www.cnblogs.com/AKMer/p/10437525.html 题目传送门:https://www.luogu.org/problemnew/show/P ...
- AngularJS:应用
ylbtech-AngularJS:应用 1.返回顶部 1. AngularJS 应用 现在是时候创建一个真正的 AngularJS 单页 Web 应用(single page web applica ...