使用实体框架核心仅编辑已更改或提及的值

问题描述 投票:1回答:3

我需要更新put请求体中提到的字段,当前的问题是,要更新的实体中未提及的所有值都设置为null,这是我在通用存储库中的currrent更新实现。

    public virtual void Update(T entity)
    {
        Context.Attach(entity);
        Context.Entry(entity).State = EntityState.Modified;
    }
asp.net-core entity-framework-core
3个回答
1
投票

您需要两个不同的步骤。首先,您必须执行修补操作。 Description here

public IActionResult PatchEntity(int id, [FromBody] JsonPatchDocument<Entity> patchdoc)
{
    var entity = dbContext.Entities.Find(e=>e.Id == id);
    patchdoc.ApplyTo(entity);
    dbContext.Update(entity);
    return Ok(entity);
}

以下是对DB(take a look at this question too)执行部分更新的方法:

public virtual void Update(params object[] keys, T entity)
{
    var current = Context.Entities.Find(keys);
    Context.Entry(entity).CurrentValues.SetValues(entity);
    Context.SaveChanges();
}

如果您不需要部分更新数据库记录,则可以使用:

public virtual void Update(T entity)
{
    Context.Update(entity); // entity is attached by default after select of entity
    Context.SaveChanges();
}

1
投票

您可以做的是在更新之前获取实体:

  1. 从您的上下文中获取您的实体
  2. 使用模型中的数据更新实体的字段。您可以使用像Automapper这样的工具以干净的方式实现这一目标。
  3. 然后在实体上调用Update方法

另一种方法是检查每个字段的状态,例如在this answer中。

编辑更新点2。

希望能帮助到你。


1
投票

终于弄清楚了,甚至没有更改存储库我只是在automapper配置文件中添加了一个配置来忽略任何空值

CreateMap<TeamDto, Team>().ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));
© www.soinside.com 2019 - 2024. All rights reserved.