【问题标题】:Entity Framework Core - REST json merge patch (Partial Update)Entity Framework Core - REST json 合并补丁(部分更新)
【发布时间】:2017-03-17 14:58:58
【问题描述】:

EF Core 支持 Json 补丁 - RFC6902

https://github.com/aspnet/JsonPatch

我想在我的应用中添加对 Json Merge Patch 的支持 - RFC7396

我是实体框架的新手。

我尝试了以下,它工作正常,但想知道实现是否正常(模型验证在过滤器中处理,所以请忽略该部分):

[HttpPatch("{id}")]
public async Task<IActionResult> Update(int id, [FromBody] TEntity updatedEntity)
{
    TEntity entity = repository.GetById<TEntity>(id);
    if (entity == null)
    {
         return NotFound(new { message = $"{EntityName} does not exist!" });
    }
    repository.Update(entity, updatedEntity);
    await repository.SaveAsync();
    return NoContent();
}

在存储库中:

public void Update<TEntity>(TEntity entity, TEntity updatedEntity) where TEntity : class, IEntity
{
    updatedEntity.Id = entity.Id;
    PropertyInfo[] properties = entity.GetType().GetProperties();
    foreach (PropertyInfo propertyInfo in properties)
    {
        if (propertyInfo.GetValue(updatedEntity, null) != null)
        {
            propertyInfo.SetValue(entity, propertyInfo.GetValue(updatedEntity, null), null);
        }
    }
    entity.ModifiedDate = DateTime.UtcNow;
    context.Entry(entity).Property(e => e.CreatedDate).IsModified = false;
}

【问题讨论】:

  • 你想做什么?
  • @H.Herzl 表的部分更新,如果请求 json 中缺少属性,则不受影响。发布的代码工作正常,基本上我希望专家对我的代码进行方法审查

标签: c# entity-framework rest entity-framework-core


【解决方案1】:

使用实体类型是一种糟糕的模式,它在外部接口(您的 api)中反映了内部架构(您的数据库)。

但对于部分更新,您可以像这样使用动态:

dynamic changedData = new { /* props you wanna change */ };
DataContext.Entry(yourEntity).CurrentValues.SetValues(changedData);

【讨论】:

  • 你可以将它用于嵌套类吗?
猜你喜欢
  • 2021-07-27
  • 2016-06-26
  • 2017-02-11
  • 2018-02-22
  • 2015-07-08
  • 2017-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多