.NET API更新包括ID [英] .NET API Update Includes ID
问题描述
我来自一个Ruby on Rails的API的背景,但我目前工作的一个.NET C#的WebAPI。我所熟悉的C#和.NET web表单。
I come from a Ruby on Rails API background, but am currently working on a .NET C# WebAPI. I am familiar with C# and .NET webforms.
我试图设置将更新数据库记录一个PUT请求。脚手架方法将覆盖所有的领域,而我想简单地更新只是通过PUT传递的字段。我试图用下面的code:
I'm attempting to set up a PUT request that will update a record in the db. The scaffolded method overwrites all the fields, whereas I want to simply update just the fields passed through the PUT. I attempted with the below code:
// PUT: api/Users/5
[ResponseType(typeof(void))]
public IHttpActionResult PutUser(string id, User user)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
User userToUpdate = db.Users.Where(u => u.id == id).FirstOrDefault();
if (userToUpdate == null)
{
return NotFound();
}
db.Entry(userToUpdate).CurrentValues.SetValues(user);
try
{
db.SaveChanges();
}
catch (DbUpdateException)
{
if (UserExists(id))
{
return Conflict();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
然而,这种方法无法对 db.SaveChanges()
,因为它不能覆盖'身份证',这是一个关键。 PUT请求是内容类型:应用程序/ JSON
和JSON是如下:
However, the method fails on db.SaveChanges()
as it cannot overwrite 'id', which is a key. The put request is of content-type: application/json
and the json is below:
{
"preferredEmailUpdates":"true"
}
这需要工作的各个领域和接受空条目。因此,下面是有效的为好,并应与空更新领域的手机。
This needs to work for all fields and accept null entries. So the below is valid as well, and should update the field phone with null.
{
"preferredEmailUpdates":"true",
"phone":null
}
如何更新这些值,而不是更新的关键?
How do I update these values, while not updating the key?
推荐答案
您可以考虑使用 PATCH
HTTP动词和的 三角洲< T>
目的。
You can consider using the PATCH
HTTP verb and a Delta<T>
object.
[AcceptVerbs("Patch"), ResponseType(typeof(void))]
public IHttpActionResult PatchUser(string id, Delta<Team> changes)
{
User userToUpdate = db.Users.Where(u => u.id == id).FirstOrDefault();
if (userToUpdate == null)
return NotFound();
changes.Patch(userToUpdate);
try
{
db.SaveChanges()
}
catch (DbUpdateException)
{
...
}
return StatusCode(HttpStatusCode.NoContent);
}
另见的的同达简易的ASP.NET Web API资源更新 的。
See also Easy ASP.NET Web API resource updates with Delta.
这篇关于.NET API更新包括ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!