如何使用 children 更新实体?补丁方法不起作用

How can I update entity with its children? Patch method doesn't work

我必须使用其 children 列表更新我的实体,如下所示:

 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;}
}

我是这样实现patch方法的:

[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);
}

但是当我尝试以这种方式从提琴手调用它时:

Url: http://localhost/odata4/Entity1(1)/  with patch request

Request Headers: Content-Type: application/json

Request Body: 
{
Name: "pippo2",
ChildrenList:[{
Nome: "Test",
Cognome: "Pippo"
}]
}

它在 Model.isValid 属性 中给出错误并指定 return 这个错误:

Cannot apply PATCH to navigation property 'ChildrenList' on entity type 'Entity1'.

我该如何解决?补丁方法是正确的使用方法吗?

OData V4 spec 表示要更新一个实体:

实体不得包含相关实体作为内联内容。它可能包含导航属性的绑定信息。对于 single-valued 导航属性,这会替换关系。对于 collection-valued 导航属性,这增加了关系。

所以,您可以使用:

  1. 更新child:

    Patch/Put: ~/Child1s(...)

  2. 更新parent

    Patch/Put: ~/Entity1s(...)

  3. 更新parent和child之间的关系:

    PATCH/PUT~/Entity1s(...)/ChildrenList/$ref

带有实体参考链接内容。