Introduction
In this blog you will learn when to use DbSet Find () method and what are benefits of using Find () in Entity framework core.
Find()
Consider the scenario where you need to get a particular object, in my case it is a user object based on the id parameter. In this case I noticed most developers will try to use the FirstorDefault() LINQ method to fetch the user based on id as in the statement given below.
- var userLinq = context.Users.FirstOrDefault(u => u.Id == 2);
In this case instead of using FirstOrDefault() we should use DbSet method Find() when filtering the entity using the key.
- var userFind = context.Users.Find(2)
Benefits of using Find()
- It’s a DbSet method
- Executes immediately
If the key is already in memory and being tracked by the context, it avoids unnecessary database queries and returns the object which is already in tracking.
- var userLinq = context.Users.FirstOrDefault(u => u.Id == 2);
- Console.WriteLine(userLinq.Name);
- var userLinq1 = context.Users.FirstOrDefault(u => u.Id == 2);
- Console.WriteLine(userLinq1.Name);
From the above figure you can notice that the top select query is generated two times based on the code written using LINQ.
- var userFind = context.Users.Find(2);
- Console.WriteLine(userFind.Name);
- var userFind1 = context.Users.Find(2);
- Console.WriteLine(userFind1.Name);
From the above figure you can notice the Top select query is generated with parameter only once, even though the Find() is called two times with the same key in the code. That's because the second time it returns the object which is already in tracking by context. If nothing is under tracking in context it will generate the new command.
Summary
We saw how the DbSet Find() method is used to optimize the querying in Entity Framework Core.
I hope you have enjoyed this blog. Your valuable feedback, questions, or comments about this blog are always welcomed.