Setting an EntityReference Using an EntityKey in Entity Framework
Setting an EntityReference Using an EntityKey
Sometimes you want to set an EntityReference but you don’t have
that entity in the ObjectContext but you have its key. One solution
for this problem is to load the entity and then to set the EntityReference.
This will make an unwanted roundtrip to the database which we would
like to avoid. The second solution is to create the EntityReference
using only its EntityKey. This solution will allow to create a foreign key
for an entity without having the related data in the ObjectContext.
One drawback for this solution is that you must know the entity key or else
you’ll get an exception.
The following example shows how to set an EntityReference using
Course course = new Course();
new EntityKey(“SchoolEntities.Departments”, “DepartmentID”, 1);
In the example I create a new course and I know that the engineering
department has a DepartmentID of 1. I make a entity reference to that
department through the created DepartmentReference property using
Let sum up, in the post I showed a simple solution that enables to set a
navigation property by using an entity key. You must pay attention that
setting an un-existing EntityKey will raise an exception. This solution
can decrease roundtrips to the database and increase the performance
for your application.