public async Task <IActionResult> PutWorkout(int id, Workout workout) { if (id != workout.Id) { return(BadRequest()); } _context.Entry(workout).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!WorkoutExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <int> UpdateAsync <T>(T entity, params Expression <Func <T, object> >[] navigations) where T : Entity { //This code is from the following URL, with a few minor modifications: //https://entityframeworkcore.com/knowledge-base/55088933/update-parent-and-child-collections-on-generic-repository-with-ef-core var dbEntity = await _context.FindAsync <T>(entity.Id); var dbEntry = _context.Entry(dbEntity); dbEntry.CurrentValues.SetValues(entity); foreach (var property in navigations) { var propertyName = property.GetPropertyAccess().Name; var dbItemsEntry = dbEntry.Collection(propertyName); var accessor = dbItemsEntry.Metadata.GetCollectionAccessor(); await dbItemsEntry.LoadAsync(); var dbItemsMap = ((IEnumerable <Entity>)dbItemsEntry.CurrentValue) .ToDictionary(e => e.Id); var items = (IEnumerable <Entity>)accessor.GetOrCreate(entity, false); foreach (var item in items) { if (!dbItemsMap.TryGetValue(item.Id, out var oldItem)) { accessor.Add(dbEntity, item, false); } else { _context.Entry(oldItem).CurrentValues.SetValues(item); dbItemsMap.Remove(item.Id); } } foreach (var oldItem in dbItemsMap.Values) { accessor.Remove(dbEntity, oldItem); } } return(await _context.SaveChangesAsync()); }