Unable to update Foreign Key in Entity Framework 6

后端 未结 4 1358
迷失自我
迷失自我 2020-12-17 03:01

I am trying to do a simple update to the foreign key but the script never get sent over.

Here is the code I am using:

using (var db = new MyContext()         


        
4条回答
  •  爱一瞬间的悲伤
    2020-12-17 03:39

    Since you are working with independent association. You can either

    • Adding and removing the relationship from ContactList, but you need to retrieve from both Person.

      db.Entry(newContact).State = EntityState.Modified;
      
      var p1 = db.Set().Include(p => p.ContactList)
          .FirstOrDefault(p =>p.Id == 1);
      p1.ContactList.Remove(newContact);
      
      var p3 = db.Set().Include(p => p.ContactList)
          .FirstOrDefault(p => p.Id == 3);
      p3.ContactList.Add(newContact);
      
      db.SaveChanges();
      
    • Or you can use disconnected object, but you need to manually manage the relationship.

      db.Entry(newContact).State = EntityState.Modified;
      
      var p1 = new Person { Id = 1 };
      db.Entry(p1).State = EntityState.Unchanged;
      var p3 = new Person { Id = 3 };
      db.Entry(p3).State = EntityState.Unchanged;
      
      var manager = ((IObjectContextAdapter)db).ObjectContext.ObjectStateManager;
      manager.ChangeRelationshipState(newContact, p1, item => item.ContactOwner,
           EntityState.Deleted);
      manager.ChangeRelationshipState(newContact, p3, item => item.ContactOwner,
           EntityState.Added);
      
      db.SaveChanges();
      

    PS

    You might need to reconsider adding foreign key value, to make everything easier, updating foreign key just by mentioning the Id.

    See this post for more information.

提交回复
热议问题