@@ -298,22 +298,31 @@ public virtual async Task<TEntity> UpdateAsync(TId id, TEntity entity)
298298
299299 if ( _jsonApiContext . RelationshipsToUpdate . Any ( ) )
300300 {
301+ /// For one-to-many and many-to-many, the PATCH must perform a
302+ /// complete replace. When assigning new relationship values,
303+ /// it will only be like this if the to-be-replaced entities are loaded
301304 foreach ( var relationship in _jsonApiContext . RelationshipsToUpdate )
302305 {
303-
304- if ( relationship . Key is HasManyAttribute && ! ( relationship . Key is HasManyThroughAttribute ) )
305- {
306- /// If we are updating to-many relations from PATCH, we need to include the relation first,
307- /// else it will not peform a complete replacement, as required by the specs.
308- relationship . Key . SetValue ( oldEntity , relationship . Value ) ;
309- } else if ( relationship . Key is HasManyThroughAttribute throughAttribute )
306+ if ( relationship . Key is HasManyThroughAttribute throughAttribute )
310307 {
311- // If we're updating many-to-many, we only have to load the ArticleTags.
312- // The new value was already set in the AttachRelationships(oldEntity) call.
313- // @TODO: It it not consistent that for many-to-many, the new relation value
314- // is assigned in a helper function, whereas for one-to-many, it happens here.
315308 await _context . Entry ( oldEntity ) . Collection ( throughAttribute . InternalThroughName ) . LoadAsync ( ) ;
316- AttachRelationships ( oldEntity ) ;
309+ }
310+ else if ( relationship . Key is HasManyAttribute )
311+ {
312+ await _context . Entry ( oldEntity ) . Collection ( relationship . Key . InternalRelationshipName ) . LoadAsync ( ) ;
313+ }
314+ }
315+ AttachRelationships ( oldEntity ) ;
316+
317+ /// @TODO: It it not consistent that for many-to-many, the new relationship value
318+ /// is assigned in AttachRelationships() helperfunction, whereas for
319+ /// one-to-many and one-to-one, we need to do it manually as below.
320+ /// As a result, we need to loop over RelationshipsToUpdate a second time.
321+ foreach ( var relationship in _jsonApiContext . RelationshipsToUpdate )
322+ {
323+ if ( ! ( relationship . Key is HasManyThroughAttribute ) )
324+ {
325+ relationship . Key . SetValue ( oldEntity , relationship . Value ) ;
317326 }
318327 }
319328 }
0 commit comments