【问题标题】:How to avoid update conflict when updating the same record at the same time同时更新同一条记录时如何避免更新冲突
【发布时间】:2017-05-28 00:46:43
【问题描述】:

我正在使用 Entity Framework 和 SQL Server 设计一个库存系统。这个应用程序将被成千上万的用户使用。如何设计允许用户同时更新相同库存数据的应用程序/数据库?目前,为了保持一致性,我使用行版本控制,但这通常会导致“更新冲突”错误。

【问题讨论】:

    标签: c# asp.net sql-server entity-framework entity-framework-6


    【解决方案1】:

    阅读有关重试模式的更多信息(here 是我的帖子)。有了它,您可以检测冲突并决定要做什么(重写、合并或向用户抛出错误)。

    使用示例:

    var retryCount = 3;
    var currentRetry = 0;
    using (var context = new DbContext(ConnectionString))
    {
        var user = context.Set<User>().First(o => o.Id == 1);
        user.Login = "newuserlogin";
        do
        {
            try
            {
                currentRetry++;
                context.SaveChanges();
                break;
            }
            catch (DbUpdateConcurrencyException ex) when (currentRetry <= retryCount)
            {
                //conflict detected
                var entry = ex.Entries.Single();
                //rewrite values from database
                entry.OriginalValues.SetValues(entry.GetDatabaseValues());
            }
        } while (true);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-09
      • 1970-01-01
      • 2020-05-16
      • 2019-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多