【发布时间】:2021-01-24 15:43:00
【问题描述】:
我在下面有一个执行 PUT 请求的 .Net Core API 控制器。
Sql Server 中受影响的表如下所示:
carID (varchar(15), NULL)
optionID (varchar(15), NOT NULL)
optionDescription (varchar(255), NULL)
optionType (varchar(50), NULL)
factoryID (varchar(15), NULL)
在测试中,我在 PUT API 调用中发送我想要更改的属性:
{
" optionID": "633fr",
"optionDescription": "Full Tech Package A"
}
它确实更新了数据库中的条目,但它还将所有未在 PUT 调用中发送的值设置为 NULL。因此,虽然它确实更新了 optionDescription,但它会将除 optionID 之外的所有其他值设置为 NULL。
如何阻止它设置其他值?
谢谢!
这里是控制器:
// PUT: api/CarOptions/5
[HttpPut("{id}")]
public async Task<IActionResult> PutCarOptions(Guid id, CarOptions carOptions)
{
if (id != carOptions.OptionId)
{
return BadRequest();
}
_context.Entry(carOptions).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!CarOptionsExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
【问题讨论】:
-
从数据库中获取记录,只修改你想要的字段,保存到数据库?
标签: asp.net-core entity-framework-core asp.net-core-webapi asp.net-core-3.1