c# - 仅更新给定值(实体框架)
问题描述
我试图仅通过动态发送到 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。我怎样才能只更新给定的?
谢谢
解决方案
您将需要使用 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 补丁文档完成。
了解有关补丁文档的更多信息
如果您也可以通过此 实体框架验证中提供的解决方案通过部分更新来实现相同的目标
推荐阅读
- javascript - 你如何为你的不和谐机器人创建一个永久的 oauth 邀请?
- php - “/tmp/phpIKaDnv”文件不存在或不可读
- r - 仅使用列名从列表中的向量返回值
- marklogic - MarkLogic如何在指定林中插入文档
- mysql - 将数据从一个表复制到另一个不避免重复键
- pandas - 如何使用列号而不是列名修改列?
- firebase - 如何从 SwiftUI 的列表中删除 Firestore 文档
- python - 获取 Django 中的当前用户不在测试中工作
- css - CSS:位置:绝对不应用 - 从流中删除元素
- c++ - Ncurses 无缘无故地使用了我所有的 CPU