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();
}