1

I need to update only mentioned fields in the put request body , the current issue is that all the values that are not mentioned in the entity to update are set to null below is my currrent update implementation in the generic repository.

    public virtual void Update(T entity)
    {
        Context.Attach(entity);
        Context.Entry(entity).State = EntityState.Modified;
    }

3 Answers3

1

What you could do is to get the entity before updating it :

  1. Get your entity from your Context
  2. Update the fields of your entity with the data from your model. You can use tools like Automapper to achieve this goal in a clean way.
  3. Then call your Update method on the entity

Another way would be to check the state of each field such as in this answer.

EDIT Update point 2.

Hope it helps.

Skrface
  • 1,388
  • 1
  • 12
  • 20
  • thanks , actually i need some clean way to do that because i have many fields checking written values and updating with new values is not an option , i think i need ti make entity framework not edit unmentionned fields or somehow merge the current values with the new once – Jawhar Jarrar Apr 16 '19 at 10:36
  • 1
    I updated the answer to mention a usefull tool you can use to merge objects (models and entities in your case). – Skrface Apr 16 '19 at 11:17
1

You need two different steps. First you have to perform a patch operation. Description here

public IActionResult PatchEntity(int id, [FromBody] JsonPatchDocument<Entity> patchdoc)
{
    var entity = dbContext.Entities.Find(e=>e.Id == id);
    patchdoc.ApplyTo(entity);
    dbContext.Update(entity);
    return Ok(entity);
}

Here is a method to perform partial update on DB (take a look at this question too):

public virtual void Update(params object[] keys, T entity)
{
    var current = Context.Entities.Find(keys);
    Context.Entry(entity).CurrentValues.SetValues(entity);
    Context.SaveChanges();
}

If you don´t need to partially update the database record you are fine with:

public virtual void Update(T entity)
{
    Context.Update(entity); // entity is attached by default after select of entity
    Context.SaveChanges();
}
Joshit
  • 1,238
  • 16
  • 38
  • using the CurrentValues function would be perfect but the repository i am using is a generic on so the the id field name would change according to the entitites – Jawhar Jarrar Apr 16 '19 at 10:26
1

finally figured it out without even changing the repository i just added a config within the automapper config file to ignore any null value

CreateMap<TeamDto, Team>().ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));