EntityReference change key
From Northwind, I want to add the following method to Product class:
public void SetCategory(int categoryID)
The problem is that from product class, I have no reference to the ObjectContext (which can be null if the product isn't attached). So it isn't possible to use Category property because we will have an exception if we set this property with a category attached to a different context than the product.
The idea is to use CategoryReference property. CategoryReference is of type System.Data.Objects.DataClasses.EntityReference<Categories> which contains a property EntityKey. We just need to change the EntityKey.
EntityKey has a property EntityKeyValues of type System.Data.EntityKeyMember. In our case, the key of Category is only the CategoryID. So we can be tempted to do this:
p.CategoryReference.EntityKey.EntityKeyValues.Value = categoryID;
but it isn't possible! Indeed EntityKeyMember is immutable, so you can't change its property Key or Value if they are affected.
So, the solution is to reinstanciate a new EntityKey:
CategoryReference.EntityKey = new EntityKey("NorthwindEntities.Categories", "CategoryID", categoryID);