How can I update an object with its children? Patch method doesn't work
I have to update my object with its child list like below:
public class Entity1
{
int Id{get;set;}
ObservableCollection<Child1> ChildrenList {get;set;}
string Name{get;set;}
}
public class Child1
{
string Nome{get;set;}
string Cognome {get;set;}
}
I applied the patch method this way:
[AcceptVerbs("PATCH", "MERGE")]
public async Task<IHttpActionResult> Patch([FromODataUri] int key, Delta<Entity1> entityDelta)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var entity = await Context.Entity1.FindAsync(key);
if (entity == null)
{
return NotFound();
}
entityDelta.Patch(entity);
try
{
await Context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
return NotFound();
}
return Updated(entity);
}
but when i try to call it from fiddler like this:
Url: http://localhost/odata4/Entity1(1)/ with patch request
Request Headers: Content-Type: application/json
Request Body:
{
Name: "pippo2",
ChildrenList:[{
Nome: "Test",
Cognome: "Pippo"
}]
}
It gives an error in Property.isValid Property and sets this error:
Cannot apply PATCH to navigation property "ChildList" for entity type 'Entity1'.
How can I solve this? Is the patch method the correct method?
source to share
OData V4 specification for object update:
An object MUST NOT contain related objects as embedded content. It MAY contain binding information for navigation properties. For unambiguous navigation properties, this replaces the relationship. For collection navigation properties, this adds a relationship.
So you can use:
-
Update child:
Patch / Put: ~ / Child1s (...)
-
Update parent
Patch / Put: ~ / Entity1s (...)
-
Update the relationship between parent and child:
PATCH / PUT ~ / Entity1s (...) / ChildrenList / $ ref
with the content of links to links.
source to share