首页 > 解决方案 > HttpPatch 未更新 .NET Core 中的数据

问题描述

我在 .NET Core 中有以下代码

小米控制器

[HttpPatch]
[Route("description/{id}")]
public Task<ActionResult<Video>> UpdateVideoDescription(int id, [FromBody]JsonPatchDocument<Video> descriptionPatch)
    {
        return _repository.UpdateVideoDescription(id, descriptionPatch);
    }

小米仓库

public async Task < ActionResult < Video >> UpdateVideoDescription(int id, JsonPatchDocument < Video > descriptionPatch) {
 var video = await _context.Videos.FindAsync(id);
 descriptionPatch.ApplyTo(video);
 await _context.SaveChangesAsync();
 return Ok(video);
}

但由于某种原因,数据库中的描述没有更新......我尝试了以下请求

{
    "op": "replace",
    "path": "/description",
    "value": "New Description"
}

{
    "description" : "New Description"
}

这些都不起作用。提前致谢。

标签: asp.net.netasp.net-core.net-core

解决方案


好像您在将对象保存到数据库之前忘记更新对象。

...
descriptionPatch.ApplyTo(video);
_context.Update(video); // add this before you save changes
await _context.SaveChangesAsync();
return Ok(video);
...

推荐阅读