繁体   English   中英

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

[英]Update Foreign key (entity) with entity framework V1

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

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

国家

  • CountryId
  • 名称

我可以添加和删除实体这是正常的。 我也可以更新名字,名字。 但我如何更新国家财产与另一个国家。

我在努力

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

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

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

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

亲切的问候Dieter

db是你的背景吗? 你应该能够做到:

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

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

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

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

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

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

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

这对我有用。 在模型中:

<%= 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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM