First, I assume
CustomObjects
is declared as a
DbSet<customobject></customobject>
in your
DbContext
class.
Here you are pulling a record from the SQL table:
var customObject = dbContext.CustomObjects.Find(Id);
Here it appears you then replacing the object you just pulled from the DB with one you (I'm assuming) created within your application:
customObject = newObject;
Finally you attempt to set the object's state to modified and save it, which doesn't work:
dbContext.Entry(customObject).State = System.Data.EntityState.Modified;
dbContext.SaveChanges();
I think your problem lies in the
customObject = newObject;
line because you are completely replacing the object you just pulled with a new object, including the primary key.
Try updating individual properties of the object instead of overwriting the object in it's entirety.
I think your example code is closer to the following:
var customObject = dbContext.CustomObjects.Find(Id);
dbContext.CustomObjects.Remove(customObject);
dbContext.SaveChanges();
dbContext.CustomObjects.Add(newObject);
dbContext.SaveChanges();