因为我不喜欢重复复杂的逻辑,所以这里提供了Slauma解决方案的通用版本。
这是我的更新方法。请注意,在分离的情况下,有时您的代码将读取数据然后更新它,因此并非总是分离的。
public async Task UpdateAsync(TempOrder order)
{
order.CheckNotNull(nameof(order));
order.OrderId.CheckNotNull(nameof(order.OrderId));
order.DateModified = _dateService.UtcNow;
if (_context.Entry(order).State == EntityState.Modified)
{
await _context.SaveChangesAsync().ConfigureAwait(false);
}
else
{
var existing = await SelectAsync(order.OrderId!.Value).ConfigureAwait(false);
if (existing != null)
{
order.DateModified = _dateService.UtcNow;
_context.TrackChildChanges(order.Products, existing.Products, (a, b) => a.OrderProductId == b.OrderProductId);
await _context.SaveChangesAsync(order, existing).ConfigureAwait(false);
}
}
}
CheckNotNull在这里定义。
创建这些扩展方法。
public static void TrackChildChanges<T>(this DbContext context, IList<T> childs, IList<T> existingChilds, Func<T, T, bool> match)
where T : class
{
context.CheckNotNull(nameof(context));
childs.CheckNotNull(nameof(childs));
existingChilds.CheckNotNull(nameof(existingChilds));
foreach (var existing in existingChilds.ToList())
{
if (!childs.Any(c => match(c, existing)))
{
existingChilds.Remove(existing);
}
}
var existingChildsCopy = existingChilds.ToList();
foreach (var item in childs.ToList())
{
var existing = existingChildsCopy
.Where(c => match(c, item))
.SingleOrDefault();
if (existing != null)
{
context.Entry(existing).CurrentValues.SetValues(item);
}
else
{
existingChilds.Add(item);
}
}
}
public static void SaveChanges<T>(this DbContext context, T model, T existing)
where T : class
{
context.CheckNotNull(nameof(context));
model.CheckNotNull(nameof(context));
context.Entry(existing).CurrentValues.SetValues(model);
context.SaveChanges();
}
public static async Task SaveChangesAsync<T>(this DbContext context, T model, T existing, CancellationToken cancellationToken = default)
where T : class
{
context.CheckNotNull(nameof(context));
model.CheckNotNull(nameof(context));
context.Entry(existing).CurrentValues.SetValues(model);
await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
}