Benefits Of Using Find () In Entity Framework Core

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.
  1. 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.

  1. 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.
  1. var userLinq = context.Users.FirstOrDefault(u => u.Id == 2);
  2. Console.WriteLine(userLinq.Name);
  3. var userLinq1 = context.Users.FirstOrDefault(u => u.Id == 2);
  4. 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.
  1. var userFind = context.Users.Find(2);
  2. Console.WriteLine(userFind.Name);
  3. var userFind1 = context.Users.Find(2);
  4. 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.

Anjali Punjab

Anjali Punjab is a freelance writer, blogger, and ghostwriter who develops high-quality content for businesses. She is also a HubSpot Inbound Marketing Certified and Google Analytics Qualified Professional.