Editing records using EF is very simple. Visual Studio even scaffolds out all of the code for you if you are simply updating a textual record. However, if you are also trying to update an image or file things get a little tricky. Trying to determine if a new file has been upload and then either delete the old image and upload the new one or repopulate the old image name so that it is not removed when the new information is updated has proven to be quite a challenge. This is because of the way the EF tracks objects. It seems that we could simply use the Find() method to look up the old image however that causes the following error:
Attaching an entity of type ‘X’ failed because another entity of the same type already has the same primary key value. This can happen when using the ‘Attach’ method or setting the state of an entity to ‘Unchanged’ or ‘Modified’ if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the ‘Add’ method or the ‘Added’ entity state to track the graph and then set the state of non-new entities to ‘Unchanged’ or ‘Modified’ as appropriate.