The property 'Id' is part of the object's key information and cannot be modified

后端 未结 15 2333
天涯浪人
天涯浪人 2020-11-27 07:02

i\'m using Entity Framework 4.0 and having a silly problem that i can\'t figure out.

I have two tables:

  1. Contact: Id (primary key), Value, ContactTypeId
15条回答
  •  囚心锁ツ
    2020-11-27 07:31

    This problem happens because you are referencing the same object more than once. This is not a limitation of EF, but rather a safety feature to ensure you are not inserting the same object with two different IDs. So to achieve what you are trying to do, is simply create a new object and add the newly created object to the database.

    ** This issue often happens inside loops. If you are using a while or foreach loop, make sure to have the New Created Object INSIDE the loop body.

    try this:

    Contact contact = dbContext.Contacts.Single(c => c.contactTypeId == 1234);
    contact.contactTypeId = 4;
    dbContext.AddObject(contact);
    dbContext.SaveChanges();
    

提交回复
热议问题