Home > Blockchain >  How to update an entity using EF core through webapi
How to update an entity using EF core through webapi

Time:10-22

controller.cs put function

[HttpPut("{id}")]
        public async Task<LookupTable> Put(int id, [FromBody] LookupTable lookuptable)
        {
            var item = await lookupRepository.UpdateLookup(id,lookuptable);
            return item;
        }

I have the following function in the repository layer:

 public async Task<LookupTable> UpdateLookup(int id, LookupTable entity)
        {
            LookupTable item = await riskDBContext.LookupTables.Where(c=> c.LookupId==id).FirstOrDefaultAsync();
            item=entity;
            var result = await riskDBContext.SaveChangesAsync();
            return item;
        }

This doesnot update. however if i change the code to:

 public async Task<LookupTable> UpdateLookup(int id, LookupTable entity)
        {
            LookupTable item = await riskDBContext.LookupTables.Where(c=> c.LookupId==id).FirstOrDefaultAsync();
            item.LookupAttribute = entity.LookupAttribute;
            var result = await riskDBContext.SaveChangesAsync();
            return item;
        }

it does update in the database. Why is it so? I have many properties in the Lookuptable. so I thought if I put item=entity all the old values will be replaced.

is there a way to update all the properties instead of assigning one by one?

CodePudding user response:

You can use Entry for assigning properties. Also better to use Find here.

public async Task<LookupTable> UpdateLookup(int id, LookupTable entity)
{
    LookupTable item = await riskDBContext.LookupTables.FindAsync(id);

    riskDBContext.Entry(item).CurrentValues.SetValues(entity);
    var result = await riskDBContext.SaveChangesAsync();
    return item;
}

This approach has disadvantage that you have to retrieve entity from database for update, but from other side, it will update not all fields in table but only changed.

CodePudding user response:

You can update the entity with Entity State set to EntityState.Modified.

Ensure that the entity's primary key property is provided with the id value which is existed in the database table.

public async Task<LookupTable> UpdateLookup(int id, LookupTable entity)
{
    riskDBContext.Entry(entity).State = EntityState.Modified;
    
    var result = await riskDBContext.SaveChangesAsync();
    
    return item;
}

Reference

Attaching an existing but modified entity to the context

  • Related