4

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;
}
2
  • What do you want to do ? Commented Jan 6, 2017 at 2:20
  • @H.Herzl Partial update of a table, if a property is missing in the request json it is not affected. The code posted works fine, basically I want the approach review of my code from experts Commented Jan 6, 2017 at 5:40

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

can you use this for nested classes?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.