简体   繁体   English

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

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

I have a small ASP.NET MVC application with the following entity objects: 我有一个带有以下实体对象的小型ASP.NET MVC应用程序:

Person

  • PersonId PERSONID
  • Name (string) 名称(字符串)
  • FirstName (string) FirstName(字符串)
  • Country (Country) 国家(国家)

Country 国家

  • CountryId CountryId
  • Name 名称

I can add and delete the entity's this works fine. 我可以添加和删除实体这是正常的。 I can also update name, firstname. 我也可以更新名字,名字。 But how can i update the country property with another country. 但我如何更新国家财产与另一个国家。

i was trying 我在努力

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

but this fires an exception {"An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key."}" 但这会触发异常{“ObjectStateManager中已存在具有相同键的对象.ObjectStateManager无法使用相同的键跟踪多个对象。”}“

even before i call SaveChanges on the datacontext. 甚至在我在datacontext上调用SaveChanges之前。

Can someone explaind how i can update this property? 有人可以解释我如何更新这个属性?

kind regards Dieter 亲切的问候Dieter

Is db your context? db是你的背景吗? You should be able to do: 你应该能够做到:

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

Or, if you don't want to query the database to get the foreign key entity you can also use an EntityKey to the same effect: 或者,如果您不想查询数据库以获取外键实体,您也可以使用EntityKey来实现相同的效果:

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

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

Code similar to this has worked for me when updating navigation properties. 在更新导航属性时,类似于此的代码对我有用。

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

Create a stub of the new country then attach it to the countries EntitySet, assign the new country to your Entity's navigational country property and call SaveChanges(). 创建新国家/地区的存根,然后将其附加到国家/地区EntitySet,将新国家/地区分配给您的实体的导航国家/地区属性并调用SaveChanges()。 Use your country EntitySet name in the AttachTo call. 在AttachTo调用中使用您的国家/地区EntitySet名称。

This is what worked for me. 这对我有用。 In the model: 在模型中:

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

In the controller: 在控制器中:

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