Using GetObjectByKey to short circuit database call

There are several ways to query for a single entity using Linq such as First or Single. For instance in the code below we are retrieving customer based on CustomerID


If you execute the above code 5 times with the same object context, EF will execute the same query 5 times. In Linq to sql, once you fetch an entity once, next time you retrieve it using First Or Single, it will check the context first and if it finds the entity in the context it will never hit the database. This feature is useful in scenarios because you would normally have a single object context for the entire request of an page and if somewhere in the page life cycle you have retrieved the object once, you really don’t want to retrieve it again. Instead you want to get the one from the context.

To mimic this behavior in Entity Framework, you can use GetObjectByKey when to retrieve a single entity by key. It does a similar appraoch where it looks for the entity with a key passed in the context. If the entity is not found in the context, it retrieves the entity from the database and starts tracking the entity. Code below shows an example

var customerkey = new EntityKey("NorthWindEntities.Customers", "CustomerID", "ALFKI");
var customer2 = db.GetObjectByKey(customerkey);
On the above code, to create an entity key, we use entity key constructor by passing in fully qualified entityset which includes entitycontainer, the property that identifies entity key and the value for the entity key. Even if you run the code several times against the same object context, there will be only a single call to the database. In the next version of Ef, we will have a method called Find on DbSet that will perform same operation. The benefit for Find is it would be strongly typed and there won’t be any string involved.

No Comments