当前位置: 首页 > 工具软件 > efcore.pg > 使用案例 >

EFcore 保存出现并发被提前修改的报错

南门意蕴
2023-12-01
    EFcore 保存出现并发被提前修改的报错

提示语言Database operation expected to affect 1 row(s) but actually affected 0 row(s).

   public static void EFExecute(Action<DbContext> executeAction, DbContext context, bool isCheckConcurrent = false)
        {
            executeAction(context);
            if (context.ChangeTracker.HasChanges())
            {
                var saved = false;
                while (!saved)
                {
                    try
                    {
                        context.SaveChanges();
                        saved = true;
                        if (context.Database.CurrentTransaction != null)
                            context.Database.CommitTransaction();
                    }
                    catch (DbUpdateConcurrencyException ex)
                    {
                        if (isCheckConcurrent) throw ex;
                        foreach (var entry in ex.Entries)
                        {
                            var databaseValues = entry.GetDatabaseValues();
                            var currentValues = entry.CurrentValues;
                            var originalValues = entry.OriginalValues;
                            var concurrencyProperties = currentValues.Properties.Where(m => m.IsConcurrencyToken);
                            concurrencyProperties.ForEach(m =>
                            {
                                originalValues[m] = databaseValues[m];
                            });
                        }
                    }
                }
            }
            context.Dispose();
        }
 类似资料: