Reputation: 9455
EF Core supports Json Patch - RFC6902
https://github.com/aspnet/JsonPatch
I wanted to add support for Json Merge Patch in my app - RFC7396
I am new to entity framework.
I tried following, it works fine, but wanted to know if the implementation is alright (model validation being handled in a filter, so please ignore that part):
[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();
}
And in the repository:
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;
}
Upvotes: 4
Views: 2543
Reputation: 21
Its a bad pattern to use entity types, which reflect an internal schema (your database) in external interfaces (your api).
but for a partial update you can use dynamic like this:
dynamic changedData = new { /* props you wanna change */ };
DataContext.Entry(yourEntity).CurrentValues.SetValues(changedData);
Upvotes: 2