如何处理Entity Framework中的DbUpdateConcurrencyException异常

简介:

1. Concurrency的作用

场景

有个修改用户的页面功能,我们有一条数据User, ID是1的这个User的年龄是20, 性别是female(数据库中的原始数据)

正确的该User的年龄是25, 性别是male

 

这个时候A发现User的年龄不对, 就给改成25, 那么在Entity Framework中,我们会这样做。

复制代码
var user = dbConext.User.Find(1);

//B用户在这里完成修改了User的性别

user.age = 25;

dbContext.SaveChanges();
复制代码

 

但是加入在上面注释处,有个B用户发现性别不对,完成了对用户性别的修改,改成male. 会出现什么结果呢。

var user = dbConext.User.Find(1);

当A执行这个代码的时候,获取的性别是female

user.age = 25;

当A执行这个代码的时候, 不知道B已经修改了这个记录的性别,这个时候A的user的性别还是female

dbContext.SaveChanges();

保存修改的时候,会把female覆盖回去,这样B用户的修改就作废了。

 

但这不是A的本意,A其实只是想修改年龄而已。

Entity Framework使用[ConcurrencyCheck] 来解决这种问题, 当标记为[ConcurrencyCheck] 的Entity属性,如果发现在从数据库中取下来和提交的时候不一致,就会出现DbUpdateConcurrencyException异常,避免错误提交。

 

2. 如何正确处理DbUpdateConcurrencyException异常

2.1 数据库优先方式

原理是在出现异常的时候,重新加载数据库中的数据,覆盖Context本地数据

复制代码
using (var context = new BloggingContext())
{
  var blog = context.Blogs.Find(1);
  blog.Name = "The New ADO.NET Blog";  
  bool saveFailed;
  do
  {
    saveFailed = false;
    try
    {
      context.SaveChanges();
    }
    catch (DbUpdateConcurrencyException ex)
    {
      saveFailed = true;
      // Update the values of the entity that failed to save from the store
      ex.Entries.Single().Reload();
    }
  } while (saveFailed);
}
复制代码

 

2.2 客户端优先方式

以Context保存的客户端数据为主,覆盖数据库中的数据

复制代码
using (var context = new BloggingContext())
{
  var blog = context.Blogs.Find(1);
  blog.Name = "The New ADO.NET Blog";
  bool saveFailed;
  do
  {
    saveFailed = false;
    try
    {
      context.SaveChanges();
    }
    catch (DbUpdateConcurrencyException ex)
    {
      saveFailed = true;
      // Update original values from the database
      var entry = ex.Entries.Single();
      entry.OriginalValues.SetValues(entry.GetDatabaseValues());
    }
  } while (saveFailed);
} 
复制代码

 

3.3 综合方式

有时候,不是非A即B的关系,我们希望综合数据库中的数据和context中修改的数据,再保存到数据库中

使用下面的CurrentValues, GetDatabaseValues(), 得到Context数据和数据库数据,重新构建一个正确的Entity,再更新到数据库中

复制代码
using (var context = new BloggingContext())
{
  var blog = context.Blogs.Find(1);
  blog.Name = "The New ADO.NET Blog";
  bool saveFailed;
  do
  {
    saveFailed = false;
    try
    {
      context.SaveChanges();
    }
    catch (DbUpdateConcurrencyException ex)
    {
      saveFailed = true;
      // Get the current entity values and the values in the database
      var entry = ex.Entries.Single();
      var currentValues = entry.CurrentValues;
      var databaseValues = entry.GetDatabaseValues();
      // Choose an initial set of resolved values. In this case we
      // make the default be the values currently in the database.
      var resolvedValues = databaseValues.Clone();
      // Have the user choose what the resolved values should be
      HaveUserResolveConcurrency(currentValues, databaseValues, resolvedValues);
      // Update the original values with the database values and
      // the current values with whatever the user choose.
      entry.OriginalValues.SetValues(databaseValues);
      entry.CurrentValues.SetValues(resolvedValues);
    }
  } while (saveFailed);
}
public void HaveUserResolveConcurrency(DbPropertyValues currentValues, DbPropertyValues databaseValues, DbPropertyValues resolvedValues) {   // Show the current, database, and resolved values to the user and have   // them edit the resolved values to get the correct resolution. }
复制代码

 

对上面方法的优化

使用DbPropertyValues总是别扭,使用Enttiy对象就会方便很多,下面就是转换成Entity对象操作的方法

 

复制代码
using (var context = new BloggingContext())
{
  var blog = context.Blogs.Find(1);
  blog.Name = "The New ADO.NET Blog";
  bool saveFailed;
  do
  {
    saveFailed = false;
    try
    {
      context.SaveChanges();
    }
    catch (DbUpdateConcurrencyException ex)
    {
      saveFailed = true;
      // Get the current entity values and the values in the database
      // as instances of the entity type
      var entry = ex.Entries.Single();
      var databaseValues = entry.GetDatabaseValues();
      var databaseValuesAsBlog = (Blog)databaseValues.ToObject();
      // Choose an initial set of resolved values. In this case we
      // make the default be the values currently in the database.
      var resolvedValuesAsBlog = (Blog)databaseValues.ToObject();
      // Have the user choose what the resolved values should be
      HaveUserResolveConcurrency((Blog)entry.Entity,
        databaseValuesAsBlog,
        resolvedValuesAsBlog);
      // Update the original values with the database values and
      // the current values with whatever the user choose.
      entry.OriginalValues.SetValues(databaseValues);
      entry.CurrentValues.SetValues(resolvedValuesAsBlog);
    }
  } while (saveFailed);
}
public void HaveUserResolveConcurrency(Blog entity,   Blog databaseValues,   Blog resolvedValues) { // Show the current, database, and resolved values to the user and have // them update the resolved values to get the correct resolution. }
复制代码

 

 


本文转自JustRun博客园博客,原文链接:http://www.cnblogs.com/JustRun1983/archive/2012/10/10/2717891.html,如需转载请自行联系原作者

目录
相关文章
|
前端开发 JavaScript Java
网易音乐网站系统|前后端分离springboot+vue实现在线音乐网站
网易音乐网站系统|前后端分离springboot+vue实现在线音乐网站
1549 0
|
关系型数据库 MySQL 数据库
MySQL中find_in_set函数的使用
1.语法 FIND_IN_SET(str,strlist) (1)str 要查询的字符串 (2)strlist 字段名; 参数以”,”分隔 如 (1,2,6,8) 查询字段(strlist)中包含(str)的结果,返回结果为null或记录 假如字符串str在由N个子链组成的字符串列表strlist 中,则返回值的范围在 1 到 N 之间。 一个字符串列表就是一个由一些被 ‘,’ 符号分开的子链组成的字符串。如果第一个参数是一个常数字符串,而第二个是type SET列,则FIND_IN_SET() 函数被优化,使用比特计算。 如果str不在strlist 或strlist 为空字符串,则返回
1154 0
MySQL中find_in_set函数的使用
|
11月前
|
监控 网络安全 调度
Quartz.Net整合NetCore3.1,部署到IIS服务器上后台定时Job不被调度的解决方案
解决Quartz.NET在.NET Core 3.1应用中部署到IIS服务器上不被调度的问题,通常需要综合考虑应用配置、IIS设置、日志分析等多个方面。采用上述策略,结合细致的测试和监控,可以有效地提高定时任务的稳定性和可靠性。在实施任何更改后,务必进行充分的测试,以验证问题是否得到解决,并监控生产环境的表现,确保长期稳定性。
607 1
|
机器学习/深度学习 算法 算法框架/工具
模型训练实战:选择合适的优化算法
【7月更文第17天】在模型训练这场智慧与计算力的较量中,优化算法就像是一位精明的向导,引领着我们穿越复杂的损失函数地形,寻找那最低点的“宝藏”——最优解。今天,我们就来一场模型训练的实战之旅,探讨两位明星级的优化算法:梯度下降和Adam,看看它们在不同战场上的英姿。
358 5
|
11月前
|
移动开发 Linux
Linux 文件与目录管理
Linux 文件与目录管理
82 3
|
开发框架 NoSQL 前端开发
在Winform项目和Web API的.NetCore项目中使用Serilog 来记录日志信息
在Winform项目和Web API的.NetCore项目中使用Serilog 来记录日志信息
|
SQL 数据处理 数据库
提升数据处理效率:深入探讨Entity Framework Core中的批量插入与更新操作及其优缺点
【8月更文挑战第31天】在软件开发中,批量插入和更新数据是常见需求。Entity Framework Core 提供了批处理功能,如 `AddRange` 和原生 SQL 更新,以提高效率。本文通过对比这两种方法,详细探讨它们的优缺点及适用场景。
460 0
|
NoSQL 安全 Redis
解决秒杀系统库存超卖问题:乐观锁与Redis分布式锁的应用
解决秒杀系统库存超卖问题:乐观锁与Redis分布式锁的应用
2815 0
|
Oracle 关系型数据库 数据库
一篇文章教你学会使用Oracle 数据库中、WITH 临时表名 AS ()语法
一篇文章教你学会使用Oracle 数据库中、WITH 临时表名 AS ()语法
710 0