.Net Core 控制器用于更新阵列,但仅包含属性



当我 PUT 到我的控制器进行更新时,我可以使用如下所示的代码来确保只更新对象中指定的那些属性。换句话说,如果我有一个具有属性 ID、X、Y 和 Z 的 ControlLinePointDto 对象,则以下内容只会更新属性 X

杰伦

{
"key" : 5,
"values" : {
"X": 1234
}
}

控制器

[HttpPut]
public async Task<IActionResult> PutControlLinePoint(int key, string values)
{
if (!ModelState.IsValid) return BadRequest(ModelState);
int id = key;
ControlLinePoint controlLinePoint = _context.ControlLinePoint.First(x => x.ControlLinePointId == key);
JsonConvert.PopulateObject(values, controlLinePoint);
if (id != controlLinePoint.ControlLinePointId) return BadRequest();
_context.Entry(controlLinePoint).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ControlLinePointExists(id)) return NotFound();
else throw;
}
return NoContent();
}

现在我想对控制线点数组执行相同的操作。我可以创建一个简单的对象 [{"key":5, "values":{"X": 1234}}],并对其进行反序列化 - 然后每个 aboce 使用我的代码,但这开始变得非常复杂。有没有更好的方法?

我能想到的最佳解决方案是将请求读取为 JArray 而不是列表。然后,我可以递归并获取每个对象的 ID。从数据库中获取对象并填充对象以仅更新相关属性。看起来像这样;

[HttpPut("UpdateControlLinePointSet")]
public async Task<IActionResult> UpdateControlLinePointSet([FromBody] JArray pointSetJson)
{
if (!ModelState.IsValid) return BadRequest(ModelState);
foreach (JToken p in pointSetJson)
{
ControlLinePoint clp = _context.ControlLinePoint.First(x => x.ControlLinePointId == (int)p["ControlLinePointId"]);
JsonConvert.PopulateObject(p.ToString(), clp);
_context.Entry(clp).State = EntityState.Modified;
}
await _context.SaveChangesAsync();
return NoContent();
}

最新更新