首页 > 代码库 > EntityFramework 学习 一 并发
EntityFramework 学习 一 并发
EntityFramework默认支持乐观并发
乐观并发中,实体加载后如果都没发生变化,ef保存该实体
首先,我们需要一个rowversion列为了控制student实体的并发问题,rowversion的数据类型为字节数组,rowversion像是自增id,
rowversion的值在数据库当中自动添加和更新
ef将在where子句中添加rowversion列,当你进行更新操作,如果rowversion的值与where子句中的值不一致,则抛出异常
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 == 1).Single(); } //User 2 also get the same student using (var context = new SchoolDBEntities()) { context.Configuration.ProxyCreationEnabled = false; student1WithUser2 = context.Students.Where(s => s.StudentID == 1).Single(); } //User 1 updates Student name student1WithUser1.StudentName = "Edited from user1"; //User 2 updates Student name student1WithUser2.StudentName = "Edited from user2";
//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"); } }
EntityFramework 学习 一 并发
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。