Entity Framework Core - REST json merge patch (Partial Update)

c# entity-framework entity-framework-core rest


EF Core supports Json Patch - RFC6902


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):

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;
1/5/2017 12:30:49 PM

Popular Answer

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 */ };
3/17/2017 6:58:58 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow