zoukankan      html  css  js  c++  java
  • 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");
        }
    }
  • 相关阅读:
    Cookie:Session,ServletContext
    thrift安装笔记
    Maven笔记
    JVM 几个重要的参数
    dbvisualizer参数设置
    Linux中如何设置java环境变量
    java.net.NoRouteToHostException: No route to host
    新上海滩感想
    也许你的种子永远不会开花,因为他是一棵参天大树
    男子给妻子做了张桌子,他病逝后家人偶然发现...
  • 原文地址:https://www.cnblogs.com/lanpingwang/p/6618897.html
Copyright © 2011-2022 走看看