使用实体框架V1更新外键(实体)

时间:2009-10-03 07:13:24

标签: c# asp.net-mvc entity-framework

我有一个带有以下实体对象的小型ASP.NET MVC应用程序:

  • PERSONID
  • 姓名(字符串)
  • FirstName(字符串)
  • 国家(国家)

国家

  • CountryId
  • 名称

我可以添加和删除实体,这样可以正常工作。我也可以更新名字,名字。 但是我如何才能与其他国家/地区更新国家/地区。

我正在尝试

p.Country = (from c in db.Country 
             where c.CountryId == countryId 
             select c).First();

但是会触发异常{“ObjectStateManager中已经存在具有相同键的对象.ObjectStateManager无法使用相同的键跟踪多个对象。”}“

甚至在我在datacontext上调用SaveChanges之前。

有人可以解释我如何更新这个属性吗?

亲切的问候 迪特

4 个答案:

答案 0 :(得分:2)

db是你的上下文吗?你应该能够做到:

p.Country = ctx.Country.First(c => c.CountryId == countryId);

或者,如果您不想查询数据库以获取外键实体,您也可以使用EntityKey来达到同样的效果:

p.CountryReference.EntityKey = new EntityKey("MyDb.Country", "CountryId", countryId);

答案 1 :(得分:0)

我使用了第二个解决方案,但我没有例外,但即使在我调用AcceptChanges之后,CountryId也没有在数据库中更改。

答案 2 :(得分:0)

与此类似的代码在更新导航属性时对我有用。

   Country country = new Country{CountryId = theNewCountryID };
    db.AttachTo("Countries", country);
    p.Country = country;
    db.Savechanges();

创建新国家/地区的存根,然后将其附加到国家/地区EntitySet,将新国家/地区分配给您的实体的导航国家/地区属性并调用SaveChanges()。 在AttachTo调用中使用您的国家/地区EntitySet名称。

答案 3 :(得分:0)

这对我有用。在模型中:

<%= Html.Textbox("Country.CountryId", Model.Countries) %> // I'm using a form model view

在控制器中:

Person originalPerson = (from p in db.PersonSet
                        where p.PersonId == updatedPerson.PersonId
                        select p).First();

Country country = (from c in db.CountrySet 
                  where c.CountryId == updatePerson.Country.CountryId 
                  select c).First();

db.Attach(country);
originalPerson.Country = country;
db.ApplyPropertyChanges(originalPerson.EntityKey.EntitySetName, updatedPerson);
db.Savechanges();
相关问题