May 15, 2009

Setting an EntityReference Using an EntityKey in Entity Framework

Yesterday I got a questionin my blog concerning the ability to set a reference to an entity in Entity Frameworkby using a foreign key that exists in my hand. The answer is described in this post.

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 EntityReferenceusing 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 Solution

The following example shows how to set an EntityReference using an EntityKey:

Course course = new Course();

course.DepartmentReference.EntityKey =

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 its EntityKey.

Summary

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.

6 comments

Thanks a lot! Now i can use the EF on a server side, thank you again. Now, I have the same problem: at the server i generated EF classes, then I create ADO.NET Data Service (using this classes), public them in intranet and add service reference to my Silverlight 2.0 application. The classes, generated by designer, have NOT references on the foreign keys. I mean, I have a Course class, I have a Course.Department property, but i have NOT the DepartmentReference. Now, I think, i have two ways, to add new Course in Silverlight:
1. use EF and get Department entity from database when i want to add new Course
2. write specialized web metod, like
[web metod]
AddCourse (String courseName, Guid departmentID)
{
there use EF on a server
}

Is this still the only way to create an entity reference without retrieving the referenced entity from the DB?
It seems a bit error prone way of doing it, and I don’t like having to use stings in my code. Do you know if their is a strongly typed way of doing this in .Net 4?