From the course: .NET Essentials: LINQ for Databases

Unlock the full course today

Join today to access over 22,400 courses taught by industry experts or purchase this course individually.

Use Find for faster search by key

Use Find for faster search by key - .NET Tutorial

From the course: .NET Essentials: LINQ for Databases

Start my 1-month free trial

Use Find for faster search by key

- [Instructor] Here's another technique to avoid unnecessary trips to the database. This is useful when you need to get an item by its key value. And that's what I'm doing here on line nine, I'm using the where extension method to query the database and retrieve an item with the product ID of four. And then I'm showing the single record and I'm doing that twice. So when I run the query I see I get the product information. There's a product information for product ID four and I got it twice. So that's great, but here's the problem. I've made two trips to the database. If you check out the SQL, you see that we made one request and then we made a second request. To mitigate this, we can work with a method on the DbSet class called find. It's listed up here at the top. You find to get an entity with the specified key value. And this will be faster if the item is cached in the context. In our case that's the DbContext.…

Contents