Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot "Add or Update" Entity because Primery key cannot be changed

I am implementing an import routine, where a user pastes a specific formatted string into an input field, which in turn gets tranformated into an entity and then put into a database.

The algorithm checks if the entity already exists and either tries to update it or insert it into the database. Inserting works fine - updating fails.

//considered existing if Name and owning user match.
if (db.Captains.Any(cpt => cpt.Name == captain.Name && cpt.User.Id == UserId))
{
    var captainToUpdate = db.Captains.Where(cpt => cpt.Name == captain.Name && cpt.User.Id == UserId).SingleOrDefault();

    db.Entry(captainToUpdate).CurrentValues.SetValues(captain);
    db.Entry(captainToUpdate).State = EntityState.Modified;
    await db.SaveChangesAsync();
 }

The problem at hand is, that written like this, it tries to update the primary key as well, (captain Id is 0, whereas captainToUpdate Id is already set) which results in an exception The property 'Id' is part of the object's key information and cannot be modified.

What do I need to change, so the enttiy gets updated properly. If it can be avoided I don't want to update every property by hand, because the table Captain contains 30ish columns.

like image 520
Marco Avatar asked May 15 '26 04:05

Marco


1 Answers

What you can do is first set the Id of captain to be the same as the Id of captainToUpdate:

captain.Id = captainToUpdate.Id;
db.Entry(captainToUpdate).CurrentValues.SetValues(captain);
await db.SaveChangesAsync();
like image 112
Martin Dekker Avatar answered May 17 '26 18:05

Martin Dekker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!