edit only changed or mentionned values with entity framework core

asp.net-core entity-framework-core

Question

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;
    }
1
1
4/16/2019 9:22:15 AM

Accepted Answer

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();
}
1
4/16/2019 10:55:14 AM

Popular Answer

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


Related Questions





Related

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