From 916ba00215bf5f3e38de2d61a714ad9e25ae5e8e Mon Sep 17 00:00:00 2001 From: meysamhadeli Date: Sat, 21 Jan 2023 03:48:54 +0330 Subject: [PATCH] refactor: Refactor handel DbUpdateConcurrencyException --- src/BuildingBlocks/EFCore/AppDbContextBase.cs | 30 +++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/src/BuildingBlocks/EFCore/AppDbContextBase.cs b/src/BuildingBlocks/EFCore/AppDbContextBase.cs index 57b4720..55dac6e 100644 --- a/src/BuildingBlocks/EFCore/AppDbContextBase.cs +++ b/src/BuildingBlocks/EFCore/AppDbContextBase.cs @@ -75,10 +75,36 @@ public abstract class AppDbContextBase : DbContext, IDbContext { return base.SaveChangesAsync(cancellationToken); } + //ref: https://learn.microsoft.com/en-us/ef/core/saving/concurrency?tabs=fluent-api#resolving-concurrency-conflicts catch (DbUpdateConcurrencyException ex) { - var data = ex.Entries.Single(); - data.OriginalValues.SetValues(data.GetDatabaseValues() ?? throw new InvalidOperationException()); + foreach (var entry in ex.Entries) + { + var proposedValues = entry.CurrentValues; + var databaseValues = entry.GetDatabaseValues(); + + if (databaseValues != null) + { + // update the original values with the database values + entry.OriginalValues.SetValues(databaseValues); + + // check for conflicts + if (!proposedValues.Equals(databaseValues)) + { + if (entry.Entity.GetType() == typeof(IAggregate)) + { + // merge concurrency conflict for IAggregate + } + else + { + throw new NotSupportedException( + "Don't know how to handle concurrency conflicts for " + + entry.Metadata.Name); + } + } + } + } + return base.SaveChangesAsync(cancellationToken); } }