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");
        }
    }
  • 相关阅读:
    Java—异常处理总结
    CSS white-space 属性
    兼容性问题的总结
    学习利用vertical-align:middle实现在整个页面居中
    多口USB HUB信号延长器 USBX-M200(针对于A客户使用时很棒吧)
    凌华运动控制卡调试记录
    记录:EPALN Electric P8 2.4.4.8366 安装记录
    一步一步创建一个动态库
    (转)VS中的路径宏 vc++中OutDir、ProjectDir、SolutionDir各种路径说明
    凌华运动控制卡的函数。
  • 原文地址:https://www.cnblogs.com/lanpingwang/p/6618897.html
Copyright © 2011-2022 走看看