views:

40

answers:

3

Hi all, 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 (foreign key to ContactType)
  2. ContactType: Id (Primary key), Type (Home, Cell, Work, etc.)

Entity Framework created the following two entities:

  1. Contact: Id, Value, ContactType (Navigation Property)
  2. ContactType: Id, Type, Contact (Navigation Property)

I'm using the following code to get the contact and update the contact type for that particular contact:

Contact contact = dbContext.Contacts.Single(c => c.Id == 12345);
contact.ContactType.Id = 3;

Throws the following exception:

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

It looks so simple! I don't get it!

Thanks in advance

+1  A: 

Try

contact.ContactType = differentContactType;

or

contact.ContactTypeId = 3;

You are trying to set the Id of the ContactType (of the Contact) to 3.

DaveShaw
A: 

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;
Caesar
Sorry, I was doing linq-sql not EF.
DaveShaw
A: 

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);

zeeshanhirani