c# - Entity Framework Core - REST json 合并补丁(部分更新)

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

EF Core 支持 Json 补丁 - RFC6902

https://github.com/aspnet/JsonPatch

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

我是 Entity Framework 的新手。

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

[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;
}

最佳答案

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

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

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

关于c# - Entity Framework Core - REST json 合并补丁(部分更新),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41484713/

相关文章:

java - 如何获得I.P.访问您的网络服务的客户端地址?

用于查找所有已安装的 Office 更新的 C# 代码

c# - 如何从 JArray 获取子对象到 ObservableCollection

c# - 如何使用 Linq 选择具有一对多关系的所有对象

asp.net-mvc - 为什么没有找到从我的类库到另一个类库的连接字符串?

c# - Entity Framework - db.SaveChanges() 错误

wordpress - WP REST API orderby meta_value

java - 使用 Rest 服务找不到 RequestParams

c# - 在 .NET 中获取远程计算机上环境变量的实际值

c# - MVC5 Web API 和依赖注入(inject)