Update foreign key (entity) with entity infrastructure V1

I have a small ASP.NET MVC application with the following entity objects:

Person

  • Personid
  • Name (string)
  • FirstName (string)
  • Country (Country)

The country

  • Countryid
  • Name

I can add and remove an object that works fine. I can also update the name, the name. But how can I renew the property of a country by another country.

I've tried

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

but this throws an exception {"An object with the same key already exists in the ObjectStateManager. ObjectStateManager cannot track multiple objects with the same key." } "

even before I call SaveChanges in the datacontext.

Can someone explain how I can update this property?

Regards, Dieter

+3
4

? :

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

, , EntityKey :

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

, , CountryId , AcceptChanges.

0

, , .

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

, EntitySet, Entity SaveChanges(). EntitySet AttachTo.

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();
0

Source: https://habr.com/ru/post/1719154/


All Articles