实体框架更新 - 上下文当前没有跟踪实体 [英] Entity Framework Update - The context is not currently tracking the entity
问题描述
我正在尝试更新一个实体,但是我收到以下错误:
I am trying to update an entity but I am getting the following error:
上下文当前没有跟踪实体。 / p>
The context is not currently tracking the entity.
我的数据库表由以下字段组成:
My DB table consists of the following fields:
fixturedate,leagueID(FK),A组(FK),B组(FK)。
fixturedate, leagueID (FK), Team A (FK), Team B (FK).
我的代码如下:
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();
}
当我做 entities.AttachTo(Fixtures ,validFixture);
我收到以下错误:
When I do entities.AttachTo("Fixtures", validFixture);
I get the following error:
上下文已经跟踪具有相同的不同实体资源Uri。
The context is already tracking a different entity with the same resource Uri.
我需要做些什么来更新灯具实体?
What do I need to do to update the fixture entity?
推荐答案
为什么没有跟踪validFixture并没有从您的代码中清除,但是您正在选择与validFixture实例具有相同ID的Fixture实体,这意味着它正在跟踪该实体通过fixture实例。
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.
基本上这意味着您可以通过fixture实例直接更新实体。尝试通过调用UpdateObject方法删除该行。
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.
这篇关于实体框架更新 - 上下文当前没有跟踪实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!