2

I am making an ASP.NET MVC application, and for actions like Edit or Details that require a single item, is it better to use myDbContext.MyDbSet.Single(i => i.Id == id) or myDbContext.MyDbSet.Find(id)? The latter is shorter, and in my opinion, cleaner without requiring the Linq method, but sources I have been reading on ASP.NET MVC seem to prefer the former.

I can't find a way to view the implementation, but if I had to guess, I'd say that Single() probably uses Find() somewhere along the way, which would indicate more method calls and somewhat inferior efficiency/performance. Is my thinking on this correct?

1 Answers1

4

The main difference is that Find() searches the first level cache of the DbContext first. If there is no hit, it will query the database. Single() will always query the database. In addition to that, Find() returns null when no entity was found. Single() will throw an exception. So the equivalent of Find() would be SingleOrDefault().

Andre Kraemer
  • 2,633
  • 1
  • 17
  • 28