我正在尝试使用 Json 补丁来更新存储在实体框架数据上下文中的实体。
我有这样的实体类 -
public class Customer
{
public Guid Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Quote> Quotes { get; set; }
}
public class Quote
{
public Guid Id { get; set; }
public int Order { get; set; }
public string Status { get; set; }
}
要将补丁应用于Customer
对象,我从数据上下文中查询源,然后应用补丁,如下所示 -
var entity = dataContext.Customers.Find(id);
patch.ApplyTo(entity);
dataContext.SaveChanges();
其中patch
包括 -
[{ "op": "replace", "path": "/name", "value": "new name" }]
这适用于源对象的简单更新,当我想修补链接实体时会出现问题,请考虑以下补丁
[{ "op": "replace", "path": "/quotes/0/status", "value": "Closed" }]
我面临的第一个问题是——
未找到路径段“0”指定的目标位置
我发现解决此问题的唯一方法是将更改从上下文中查询实体的方式称为 -
var entity = dataContext.Customers
.Include(ent => ent.Quotes)
.SingleOrDefault(ent => ent.Id == id);
entity.Quotes = entity.Quotes.OrderBy(ent => ent.Order).ToList);
这不太理想,因为我不喜欢查询数据来更新它的想法。我想知道是否有更清洁的方法。