首页 > 解决方案 > 仅更新给定值(实体框架)

问题描述

我试图仅通过动态发送到 API 的值来更新实体,因此每次客户端向我的 api 发送不同的值时,它只会更改给定的值。

这是我的实体

    public class Administrator
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public string Role { get; set; }
        public int Phone { get; set; }
    }

这是我的存储库:

public Task<bool> UpdateAdmin(Administrator admin)
        {
            if (admin != null)
            {
                _context.Admins.Update(admin);
                Commit();
                return Task.FromResult(true);
            }
            else
            {
                return Task.FromResult(false);
            }
        }

假设我只想更新电话号码,我只使用新电话号码发送数据,但其余属性也更改为 null。我怎样才能只更新给定的?

谢谢

标签: c#asp.net-coresql-server-2005entity-framework-core

解决方案


您将需要使用 JsonPatchDocument

这是我做类似事情的示例代码

//get the instance of admin you want to update
var adminInstance = GetAdmin....//get your admin

//partial update -> this how you create a patch doc with C#
var patchDoc = new JsonPatchDocument<Admin>();
patchDoc.Replace(x => x.phone, "put new phone number");//for any other property do x.propertyName
patchDoc.ApplyTo(adminInstance)// apply the patch doc to the instance you want to update
await UpdateAdmin(adminInstance)//your update method look good

//for people trying to do this with an api serialize the patch doc then send it to api
var adminDto =JsonConvert.SerializeObject(patchDoc);



//this is an api example
[HttpPatch("{adminId}")]
public async Task<ActionResult> UpdateAdmin(string adminId, JsonPatchDocument<Admin> patchDocument)
{
  var admin= await _adminRespository.GetAsync(admin);//get the admin you want to update

  patchDocument.ApplyTo(admin); //apply patch doc to the admin

  await _adminRespository.UpdateAsync(admin); //pass admin to your repo

  await _adminRespository.SaveAsync();

  return NoContent();
  }

在存储库中,您不必做任何复杂的事情,只需将模型作为更新传递,所有工作都由 json 补丁文档完成。

了解有关补丁文档的更多信息

http://jsonpatch.com/

如果您也可以通过此 实体框架验证中提供的解决方案通过部分更新来实现相同的目标


推荐阅读