Joe
Joe

Reputation: 1214

SaveChanges doesn't save changes

I have an application that loads all the data as expected using EF, however, when it comes to saving, I can't get it to work at all.

I've started off simple, by just using a value from a combobox to alter 1 field in the database. When the value is changed, it executes

this.t.Incident.AssignedTeamID = (int)this.cbTeam.SelectedValue;

I've also confirmed that this changed the EntityState to Modified and that the value is what I expect it to be. Despite this, calling

hdb.SaveChanges();

doesn't save anything back to the database. I know it's probably something simple I'm missing, but I cannot find out what that is at all.

Update: Adding hdb.context.Attach(this.t.Incident); before using SaveChanges results in an InvalidOperationException stating "An entity object cannot be referenced by multiple instances of IEntityChangeTracker."

If it makes any difference, this is a desktop application, not a web application

Upvotes: 1

Views: 3059

Answers (2)

Joe
Joe

Reputation: 1214

Thank you to everybody who posted here. The answer was quite simple after reading these details.

What I needed to do, as Damien commented on the original question, was to ensure it was all loaded from the same class. I currently created a private instance of the DB whenever needed, without really thinking. This was fine, it loaded the data as I expected, but meant that I would have around 3 different instances of the database loaded via different classes.

Essentially, I was trying to save the object from a different class with a different instance of the database. Moving the save method back to the class it was created from (presumably like it should have always been) resolved the issue.

Upvotes: 0

Jarrett Meyer
Jarrett Meyer

Reputation: 19593

Most likely, since you're working with a web app, you have a problem with a disconnected obect context. With all ORMs, you must go through an attach process to update an entity. SaveChanges will never work on both sides of the request/response.

Upvotes: 2

Related Questions