Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
One task that developers perform frequently is retrieving an
entity by providing its key value. For example, you may have access to
the PersonId value of a Person in a variable named _personId and would like to retrieve the
relevant person data.
Typically you would construct and execute a LINQ to Entities
query. Here’s a query that uses the SingleOrDefault LINQ method to filter on
PersonId when executing a query on
context.People:
context.People.SingleOrDefault(p => p.PersonId == _personId)
Have you written that code so often that you finally wrote a
wrapper method so you could pass the key value in and it would execute
the LINQ query for you? Yeah, us too. Now DbSet has that shortcut built in with the
Find method, which will return an
entity whose key property matches the value passed into the
method: