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 ...
随机推荐
- 康托展开与逆康托展开模板(O(n^2)/O(nlogn))
O(n2)方法: namespace Cantor { ; int fac[N]; void init() { fac[]=; ; i<N; ++i)fac[i]=fac[i-]*i; } in ...
- C#进阶之路(五):Linq初识
关于LINQ的文章,网上有很多,所以这篇文章我主要是总结下我自己的学习心得. 首先需要先了解的相关技术 1.隐式类型.匿名类型.对象初始化器 1)隐式类型,使用var关键字创建,C#编译器会根据用于初 ...
- Restoring Road Network(Floyd算法的推广)
个人心得:看懂题目花费了不少时间,后面实现确实时间有点仓促了,只是简单的做出了判断是否为真假的情况, 后面看了题解发现其实在判断时候其实能够一起解决的,算了,基础比较差还是慢慢的来吧. 题意概述: 就 ...
- jquery.tmpl的使用
jquery.tmpl是jQuery模板插件,http://plugins.jquery.com/tmpl/ (另外还有一个插件dot.js,不依赖与jquery,性能更佳,使用方法大同小异) 在网页 ...
- FastAdmin 的 Bootstrap-Table 如何合并字段?
FastAdmin 的 Bootstrap-Table 如何合并字段? ★hey-成都 14:13:34 把下面那个字段合并到上面那个字段是用什么方法 ^★暗物质-江西 14:17:21 city加上 ...
- 通过Python查看Azure VM的状态
Azure的管理平台采用Restful API的方式实现管理.比如获取VM的管理API的各种操作的文档请参考: https://docs.microsoft.com/en-us/rest/api/co ...
- 断路器(CircuitBreaker)设计模式
断路器是电器时代的一个重要组成部分,后面总是有保险丝熔断或跳闸的断路器是安全的重要保障. 微服务最近几年成为软件架构的热门话题,其益处多多.但需要知道的是,一旦开始将单块系统进行分解,就上了分布式系统 ...
- PostgreSQL 9.5 客户端认证
PostgreSQL 9.5 客户端认证 当一个客户端应用连接一个数据库服务器时,它将指定以哪个PostgreSQL 数据库用户名连接,就像我们以一个特定用户登录一台 Unix 计算机一样.在 SQL ...
- Oracle session出现大量的inactive
一.官网说明 1.1 processes 11gR2 的文档: Property Description Parameter type Integer Default value 100 Modifi ...
- mybatis如何防止sql注入(1)
sql注入大家都不陌生,是一种常见的攻击方式,攻击者在界面的表单信息或url上输入一些奇怪的sql片段,例如“or ‘1’=‘1’”这样的语句,有可能入侵参数校验不足的应用程序.所以在我们的应用中需要 ...