.Net Core控制器更新数组,但仅具有包含的属性 [英] .Net Core controller to update array, but only with included properties

查看:165
本文介绍了.Net Core控制器更新数组,但仅具有包含的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I PUT to my controller for an update, I can use code like the following to ensure that only those properties that are specified in the object are updated. In other words, if I had a ControlLinePointDto object with properties ID, X, Y and Z, the following would only update property X

JSON

{
    "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}}]的对象,并将其反序列化-然后每次都使用我的代码,但这开始变得非常复杂.有更好的方法吗?

Now I want to do the same for an array of controllinepoints. I could create an object that was simply [{"key":5, "values":{"X": 1234}}], and deserialize it - then utilize my code per aboce, but this is starting to get pretty complex. Is there a better way?

推荐答案

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

The best solution I could come up with involves reading the request as a JArray rather than a List. I can then recurse and get the ID for each object. Get the object from the database and PopulateObject to just update the relevant properties. Looks something like this;

    [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();
    }

这篇关于.Net Core控制器更新数组,但仅具有包含的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆