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

后端 未结 15 2187
天涯浪人
天涯浪人 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:53

    For me the issue was caused by the lack of a Primary Key to my table, after setting a PK for the table the problem was gone

    0 讨论(0)
  • 2020-11-27 07:55

    The entity that was created by the framework doesn't have a contact.ContactTypeId property. It automatically removed it and created the ContactType association inside the Contact entity.

    The way to get it to work, as you suggested, is to create a ContactType object by querying the database and assigning it to contact.ContactType. For example:

    Contact contact = dbContext.Contacts.Single(c => c.Id == 12345);
    ContactType contactType = dbContext.ContactType.Single(c => c.Id == 3);
    contact.ContactType = contactType;
    
    0 讨论(0)
  • 2020-11-27 07:58

    In my case, I was creating an object declared and initialized together. I just initialized in the constructor or what you can initialize the object when required.

    0 讨论(0)
提交回复
热议问题