Are Find and Where().FirstOrDefault() equivalent?

Thomas McNamee picture Thomas McNamee · Feb 6, 2013 · Viewed 16.7k times · Source

I have been using the Find(id) extension method with collections in Entity Framework 5. However, many of the examples I see use Where(s => s.Id == 1), to which I added FirstOrDefault() to get the object instead of a collection. Is this a style difference, or is there a functional reason for the apparent .Where() preference?

Answer

Judo picture Judo · Feb 6, 2013

Find() has a fundamental difference to Where(), Single(), First() etc. in that it will first search for the object in memory and only hit the database if the object has not already been loaded. Thus try to use Find() where possible as it offers possible speed benefits of loading from memory. Find() only works with the primary key and doesn't support lambdas so it is not very flexible.

Where() is typically used to get a listing of objects. To retrieve a single object I normally use either Single(), SingleorDefault(), First(), FirstorDefault().

Single() and SingleOrDefault() differ from First() and FirstOrDefault() as they ensure that a maximum of one object can satisfy the criteria which helps ensure the integrity of the data in the database. They 'Single' clauses do this by selecting 'TOP 2' in the SQL query and then throwing an exception if two entities are returned.

Note that you should not chain these to the end of the Where() clause.

So instead of

.Where(s => s.Id == 1).FirstOrDefault();

use:

.FirstOrDefault(s => s.Id == 1);

I wrote a blog post to fully explore this issue : http://judeokelly.com/primer-on-selecting-data-using-entity-framework/