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

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

    There are two types of associations. Independant association where the related key would only surface as navigation property. Second one is foreign key association where the related key can be changed using foreign key and navigation property. So you can do the following.

    //option 1 generic option

    var contacttype = new ContactType{Id = 3};
    db.ContactTypes.Attach(contacttype);
    customer.ContactType = contacttype;
    

    option 2 foreign key option

    contact.ContactTypeId = 3;
    

    //generic option works with foreign key and independent association

    contact.ContactReference.EntityKey = new EntityKey("container.contactset","contacttypeid",3);
    

提交回复
热议问题