public override async Task <OrderDto> UpdateAsync(EditOrderDto input) { var builder = new DbContextOptionsBuilder <JewelleryDbContext>(); var conn = _configuration.GetConnectionString("Default"); builder.UseSqlServer(conn); using var context = new JewelleryDbContext(builder.Options); using var transaction = context.Database.BeginTransaction(); var orderEntity = ObjectMapper.Map <Order>(input); var existingOrder = await context.Orders.Include(s => s.OrderDetails).FirstOrDefaultAsync(x => x.Id == input.Id); context.Entry(existingOrder).CurrentValues.SetValues(orderEntity); foreach (var detail in orderEntity.OrderDetails) { detail.OrderId = orderEntity.Id; var existingDetail = existingOrder.OrderDetails.FirstOrDefault(s => s.ProductId == detail.ProductId); if (existingDetail == null) { existingOrder.OrderDetails.Add(detail); } else { context.Entry(existingDetail).CurrentValues.SetValues(detail); } } foreach (var detail in existingOrder.OrderDetails) { if (!orderEntity.OrderDetails.Any(p => p.ProductId == detail.ProductId)) { context.Remove(detail); } } await context.SaveChangesAsync(); // Commit transaction if all commands succeed, transaction will auto-rollback // when disposed if either commands fails transaction.Commit(); var result = await context.Orders.Include(s => s.OrderDetails).FirstOrDefaultAsync(x => x.Id == input.Id); return(ObjectMapper.Map <OrderDto>(result)); }