Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Find vs. Where

Is there a significant difference between .Find(id) and .Where(x = >x.Id == id) that should compel me to use .Find() over .Where()/.First()?

I would imagine that .Find() would be more efficient but is it so much more efficient that I should avoid .Where()/.First()?

The reason I ask is that I am using a generic FakeDbSet in my tests to make it easy to implement fake results and so far I have found that I must inherit that class and provide a custom implementation of .Find() whereas if I write my code with .Where()/.First() I don't need to do that extra work.

like image 829
Jimmy Bosse Avatar asked Jun 06 '13 15:06

Jimmy Bosse


People also ask

How do I use Find in Entity Framework?

The Find method on DbSet uses the primary key value to attempt to find an entity tracked by the context. If the entity is not found in the context then a query will be sent to the database to find the entity there. Null is returned if the entity is not found in the context or in the database.

What is the difference between FirstOrDefault and find?

The key thing to notice here is that FirstOrDefault is called on Enumerable whereas Find is called as a method on the source list. So it's iterating over an array of items which makes sense, since a list is a wrapper on an array.

What is a DbSet?

A DbSet represents the collection of all entities in the context, or that can be queried from the database, of a given type. DbSet objects are created from a DbContext using the DbContext.


1 Answers

The point is that Find() starts by searching in the local cache of the context and then, if no match, sends a query to the DB.

Call to Where() always sends a query to the DB.

With EF 4, I used to think that SQL generated by Find() was too complex and, in some cases, led to a performance issue. So I always use Where() even with EF 5. I should check the SQL generated by Find() with EF 5.

So on paper, Find() is better because it uses the cache.

like image 133
tschmit007 Avatar answered Oct 12 '22 06:10

tschmit007