【发布时间】: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