Entity Framework Update - The context is not currently tracking the entity

狂风中的少年 提交于 2020-01-04 04:12:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!