0

Using Entity Framework I can't get the foreign key to change when I do db.SaveChanges().

In the example below 'Salutation' is a foreign key in the 'person' model.

E.g If it is currently {"Id":2,"Name":"Mrs"}, if I pass in {"Id":3,"Name":"Mr"}, which exists already, it won't change, though if I pass in {{"Id":3,"Name":"Random"}, it will change and will also update the foreign key. It will only change if there have been actual changes to the data contained rather than just the foreign key.

db.Entry(person.FirstName).State = EntityState.Modified;
db.Entry(person.LastName).State = EntityState.Modified;
db.Entry(person.Salutation).State = EntityState.Modified;

try
  {
    db.SaveChanges();
  }....

In this case 'person' is being passed in something like this:

{"FirstName": "Anne", "LastName": "Other","Salutation":{"Id":2,"Name":"Mrs"}}

Any help would be most appreciated as I've been stuck on this for months now and my previous post has not had any useful answers. Also see this post for more details on the model first DB structure etc.:

Entity Framework - not updating referenced model

Community
  • 1
  • 1
Holland Risley
  • 6,969
  • 9
  • 25
  • 34

1 Answers1

0

Change the foreign key then

db.Entry(person).State=EntityState.Modified

before

db.SaveChanges();
fikeus
  • 61
  • 5