Thursday, March 18, 2010

How to determine if Navigation Property in the Entity Framework is set without loading the related record.

Boy that is a long title. There are times (particularly with a Domain Service) that you may want to just check if an Navigation Property has a related record or not. If you just check the Navigation Property for null then you can really mess things up because if you don’t explicitly load the related record, it will be null. It is often a waste to load the related record just to save, etc.

Luckily, there is an easy solution. In fact, it also provides you with the actual foreign key value (if there is one). This can be useful for other things. The Entity Framework removes foreign key properties from the Scalar Properties section of the entity. At first glance it appears that you no longer have access to the foreign key value.

The solution is quite simple. Let’s assume we have two entities. One is Department and it has a relationship (Navigation Property) called Manager that points to the Person entity. What I propose is we do the following to determine if the Manager Navigation Property on Department points to anything.

bool isMgr = myDept.ManagerReference.EntityKey != null;

That is it. So simple, but a little hidden. You can also get the actual key values if you access the properties on the EntityKey property.

1 comment:

Jose Manuel said...

Great Post it's ilustrated to me some misundertood concepts.