Venkat
Venkat

Reputation: 2156

EF Core - How to update an entity

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 does not 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 them one by one?

Upvotes: 0

Views: 2184

Answers (2)

Svyatoslav Danyliv
Svyatoslav Danyliv

Reputation: 27282

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.

Upvotes: 1

Yong Shun
Yong Shun

Reputation: 51125

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

Upvotes: 3

Related Questions