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

c# entity-framework entity-framework-6

Question

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.

1
1
8/28/2014 8:20:07 AM

Accepted Answer

I would not use the entity Captain to transfer the data to the UI, but a DTO object that has all properties you want to copy and no more. You can copy values from any object. All matching properties will be copied, all other properties in captainToUpdate will not be affected.

2
8/28/2014 10:18:41 PM

Popular Answer

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


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