我必须使用子列表更新我的实体,如下所示:
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;}
}
我以这种方式实现了补丁方法:
[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属性中出错并指定返回此错误:
无法将PATCH应用于导航属性&#39; ChildrenList&#39;在实体上 输入&#39; Entity1&#39;。
我该如何解决?补丁方法是否使用正确的方法?
答案 0 :(得分:6)
OData V4 spec表示更新实体:
实体绝不包含相关实体作为内联内容。它可能包含导航属性的绑定信息。对于单值导航属性,这将替换该关系。对于集合值导航属性,这会增加关系。
所以,你可以使用:
更新孩子:
Patch / Put:〜/ Child1s(...)
更新父
Patch / Put:〜/ Entity1s(...)
更新父母与子女之间的关系:
PATCH / PUT~ / Entity1s(...)/ ChildrenList / $ ref
使用实体引用链接内容。