Editorials

Find or Select

I’ve been reading a lot lately about the difference in Entity Framework for finding records based on the primary key. The.Find method has been tuned to locate the record. However, some find better performance using a Linq To SQL query. The difference can be rather dramatic.

When using a Linq query a round trip to the database is ALWAYS executed. As a result, if you wish to gather data from other tables in the same statement, you can use the .Include operation, when using a Linq query.

However, if you use the .Find operation, Entity Framework takes a different approach. When using find, if the record you are seeking already exists in cache (you database context) it will resolve the request from the data found in cache. Otherwise, it will make a round trip to the database, just like the Linq query. If the data is already in Cache, Find can be faster. If not, it can take longer. It all depends.

Because the Find operation returns the object from cache, it does not support the .Include operation. If the object in cache already contains child data, then it will be there. The is no point for using .Include. In contrast, making a new call to the database through Linq, .Include is supported to gather data at the same time for tables based on a child foreign key relationship. In fact, unless you have lazy loading turned on, that’s the only way to return child data while retrieving a parent object, using one query.

Do you take time to tune your Entity Framework queries for performance? Why not get into the conversation, and share a comment about your tuning experience.

Cheers,

Ben