I am trying to use Json patches to update entities stored in an Entity Framework data context.
I have entity classes like so -
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; }
}
To apply the patch onto a Customer
object, I query the source from the data context, then apply the patch, like so -
var entity = dataContext.Customers.Find(id);
patch.ApplyTo(entity);
dataContext.SaveChanges();
Where patch
consists of -
[{ "op": "replace", "path": "/name", "value": "new name" }]
This works fine for simple updates on the source object, the problem arises when I want to patch onto the linked entities, consider the following patch
[{ "op": "replace", "path": "/quotes/0/status", "value": "Closed" }]
The first issue that I am faced with is -
The target location specified by path segment '0' was not found
The only way around this I have found is to call the alter the way of querying the entity from the context to -
var entity = dataContext.Customers
.Include(ent => ent.Quotes)
.SingleOrDefault(ent => ent.Id == id);
entity.Quotes = entity.Quotes.OrderBy(ent => ent.Order).ToList);
Which is less than ideal, as I don't like the idea of querying data to update it. I'm wondering if there is a cleaner approach to this.