我正在尝试使用 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();
Where 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);
这不太理想,因为我不喜欢查询数据来更新它的想法。我想知道是否有更干净的方法来解决这个问题。