I use Entity Framework in asp.net MVC 5 (vb.net) to store some data including an image (png). The images can be saved to the database as Byte(), but as soon I edit any existing entity without uploading a new image, the stored image is deleted. So I tried this and wrote following code in the edit controller:
If ModelState.IsValid Then
If Request.Files("Image").ContentLength <> 0 Then
dbModel.Image = dbModel.ImageToByte(Request.Files("Image")) 'Function to create Byte() --> this works
Else
dbModel.Image = db.Content.Find(dbModel.ID).Image 'This line is responsible for the exception
End If
db.Entry(dbModel).State = EntityState.Modified 'Here the exception occours!
db.SaveChanges()
Return RedirectToAction("Index")
End If
In the line, where the EntityState is set to Modified, an exception occured:
An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code
Additional information: Attaching an entity of type 'myDatabase.dbModel' 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.
I guess, that the line where the existing image is loaded from the database is responsible for the exception, but I really don't know what to do.