将JsonPatchDocument移到复杂的Entity Framework跟踪对象上 [英] JsonPatchDocument onto a complex Entity Framework tracked object

查看:69
本文介绍了将JsonPatchDocument移到复杂的Entity Framework跟踪对象上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Json补丁来更新存储在Entity Framework数据上下文中的实体.

I am trying to use Json patches to update entities stored in an Entity Framework data context.

我有这样的实体类-

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 对象上,我从数据上下文中查询源,然后应用补丁,就像这样-

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();

其中 patch 由-

[{ "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 -

找不到路径段'0'指定的目标位置

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.

推荐答案

这是我找到的解决方案- https://gist.github.com/brendanmckenzie/a50f4eb7d5913372d01fef8e73c5dc9b

This is the solution I landed on - https://gist.github.com/brendanmckenzie/a50f4eb7d5913372d01fef8e73c5dc9b

该代码处理创建和更新存储在实体框架中的实体.当EF跟踪JsonPatch应用的更改时,修补工作效果很好.

The code handles creating and updating entities stored in Entity Framework. Patching works well as EF tracks the changes applied by JsonPatch.

其中还有一些杂乱的代码( NormaliseOperations ),有助于处理链接的实体;即例如 Quote 引用另一个实体的示例.

There is some additional code in there that's a bit messy (NormaliseOperations) that helps deal with linked entities; i.e., example if Quote referenced another entity.

这篇关于将JsonPatchDocument移到复杂的Entity Framework跟踪对象上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆