EF Core 支持 Json Patch - RFC6902
https://github.com/aspnet/JsonPatch
我想在我的应用程序中添加对 Json 合并补丁的支持 - 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;
}
使用实体类型是一种糟糕的模式,它反映了外部接口(您的 API)中的内部架构(您的数据库)。
但是对于部分更新,您可以像这样使用动态:
dynamic changedData = new { /* props you wanna change */ };
DataContext.Entry(yourEntity).CurrentValues.SetValues(changedData);