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 ...
随机推荐
- Android Volley完全解析(四),带你从源码的角度理解Volley
转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/17656437 经过前三篇文章的学习,Volley的用法我们已经掌握的差不多了,但是 ...
- UVALive - 3211 Now or later (二分+2SAT)
题目链接 题意:有n架飞机,每架飞机有两个着陆时间点可以选,要求任意两架飞机的着陆时间之差不超过k,求k的最大值. 解法:由于每架飞机都有两个选择,并且必选且只能选其中一个,时间冲突也是发生在两架飞机 ...
- vue-router导航守卫
导航守卫 译者注 “导航”表示路由正在发生改变. 正如其名,vue-router 提供的导航守卫主要用来通过跳转或取消的方式守卫导航.有多种机会植入路由导航过程中:全局的, 单个路由独享的, 或者组件 ...
- linux查询组与用户getent
getent group zabbix getent passwd zabbix getent group zabbix > /dev/null || groupadd -r zabbixget ...
- 皮肤和DLL和图片等项目文件完全整合到exe中
C#开发的程序原生界面实在是太丑了,自己又没有美化天赋,所以只能使用皮肤控件了,网上找到了IrisSkin2,包含一个.dll文件和若干ssk后缀的皮肤文件,代码其实很简单的.但是后来发现个问题,就是 ...
- Git在不同环境换行符设置
首先我们在eclipse查看两个环境文件的换行符区别: 产生背景 关于“回车”(carriage return)和“换行”(line feed)这两个概念的来历和区别.在计算机还没有出现之前,有一种叫 ...
- CentOS7.2 GitLab部署
1.使用安装包的方式安装gitlab # vim /etc/yum.repos.d/gitlib.repo [gitlab-ce] name=gitlab-ce baseurl=http://mirr ...
- 第八篇 web开发学习资源
互联网时代,最好的资源都在网上,好好利用网络学起来! 偶然才发现好资源,很多是E文的,看来努力的路还很长! 1)下面是一个老外收集的PHP资源,确实要为此分享点赞. https://github.co ...
- 由于簇计数比预计的高,格式化操作无法完成——Allocation Unit Size Adjustments for Larger NTFS Volumes.
Allocation Unit Size Adjustments for Larger NTFS Volumes. Problem: When trying to format a new vol ...
- AngularJS中的http服务的简单用法
我们可以使用内置的$http服务直接同外部进行通信.$http服务只是简单的封装了浏览器原生的XMLHttpRequest对象. 1.链式调用 $http服务是只能接受一个参数的函数,这个参数是一个对 ...