问题
I am trying to update an entity but I am getting the following error:
The context is not currently tracking the entity.
My DB table consists of the following fields:
fixturedate, leagueID (FK), Team A (FK), Team B (FK).
My code is as follows:
public void UpdateFixture(Fixture validFixture)
{
Fixture fixture = new Fixture();
fixture = entities.Fixtures.Where(f => f.fixtureId == validFixture.fixtureId).FirstOrDefault();
League league = new League();
league.LeagueId = validFixture.leagueId;
fixture.League = leagueActions.GetLeague(league);
fixture.Team1 = teamActions.GetTeam(validFixture.teamA);
fixture.Team2 = teamActions.GetTeam(validFixture.teamB);
entities.UpdateObject(validFixture);
entities.SaveChanges();
}
When I do entities.AttachTo("Fixtures", validFixture);
I get the following error:
The context is already tracking a different entity with the same resource Uri.
What do I need to do to update the fixture entity?
回答1:
Why the validFixture is not tracked is not clear from your code, however you are selecting a Fixture entity with the same ID as the validFixture instance, which means it is now tracking that entity via the "fixture" instance.
Basically this means that you can update the entity via the "fixture" instance directly. Try just removing the line with the call to the UpdateObject method.
来源:https://stackoverflow.com/questions/8547783/entity-framework-update-the-context-is-not-currently-tracking-the-entity