通过 Entity Framework 和 JSON 动态更新某些属性 (C#)

Dynamically updating certain properties through Entity Framework and JSON (C#)

我有一个 .NET Core API,它应该使用 Entity Framework Core 更新数据库中的实体。

当用户编辑现有条目时,编辑表单仅发回编辑后的数据,而不是完整的实体。

假设我们有一家商店:

public class Shop {
    public int ShopID { get;set;}
    public string Name { get;set;}
    public string Address { get;set;}
}

现在,用户编辑地址并保存。发送回 API 的数据将是 ShopID 和地址。但是,使用下面的模型绑定会将 Name 设置为 NULL,这是合乎逻辑的,因为它实际上并未传入。

[Route("~/shop/[action]")]
public IActionResult Update([FromBody] Shop shop)
{
    _context.Shops.Update(shop);
    _context.SaveChanges();
    return new JsonResult(new { result = true });
}

所以,由于我不知道哪个 property/ies 可能会被更新(实际上,还有更多的属性),我需要一些方法来动态更新 [=30] 中发送的字段=]请求。

提前致谢。

DbSet<T>不包含方法Update,所以你应该先加载实体,然后更改属性值,然后调用SaveChanges:

[Route("~/shop/[action]")]
public IActionResult Update([FromBody] Shop shop)
{
    var shopData = _context.Shops.Single(s => s.Id == shop.ShopId);

    if (shop.Name != null)
        shopData.Name = shop.Name;

    if (shop.Address != null)
        shopData.Address = shop.Address;

    _context.SaveChanges();
    return new JsonResult(new { result = true });
}

因为检查和复制每个 属性 很烦人,您可以使用像 Automapper:

这样的库
[Route("~/shop/[action]")]
public IActionResult Update([FromBody] Shop shop)
{
    var shopData = _context.Shops.Single(s => s.Id == shop.ShopId);

    // Copying properties to existing object
    mapper.Map<Shop, Shop>(shop, shopData);

    _context.SaveChanges();
    return new JsonResult(new { result = true });
}

要跳过空属性,请参阅答案 Automapper skip null values with custom resolver

我没有测试过,但代码应该如下所示:

var entry = _context.Shops.Update(shop);
foreach (var property in entry.Entity.GetType().GetTypeInfo().DeclaredProperties)
{
      var currentValue = entry.Property(property.Name).CurrentValue;
      if (currentValue == null)
            entry.Property(property.Name).IsModified = false;
}