首页 > 代码库 > 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 学习 一 并发