Advertisement
Intermediate .NET, Entity Framework Core & Data Access

What is the difference between First(OrDefault) and Single(OrDefault) in EF Core queries, and when should you use each?

Short answer

First(OrDefault) returns the first matching element (or default if none/OrDefault variant) without requiring uniqueness, generating SQL with TOP 1/LIMIT 1 -- appropriate when you expect possibly multiple matches but only care about one.

Save .NET mock interview
Advertisement
AModel answer
First(OrDefault) returns the first matching element (or default if none/OrDefault variant) without requiring uniqueness, generating SQL with TOP 1/LIMIT 1 -- appropriate when you expect possibly multiple matches but only care about one. Single(OrDefault) throws an exception if more than one element matches, expressing the semantic guarantee that exactly one (or zero, for OrDefault) result is expected -- appropriate for lookups by unique key, where multiple matches would actually indicate a data integrity bug worth surfacing loudly rather than silently picking one.
// Appropriate when uniqueness isn't guaranteed or doesn't matter
var mostRecentOrder = await context.Orders.OrderByDescending(o => o.Date).FirstOrDefaultAsync();

// Appropriate when uniqueness IS expected and violations should be caught
var user = await context.Users.SingleOrDefaultAsync(u => u.Email == email);  // Email should be unique
Real-world example
A bug where a supposedly-unique email lookup was silently returning inconsistent results was caught immediately after switching from FirstOrDefault to SingleOrDefault, which threw an exception revealing a data integrity issue -- duplicate email rows that violated an assumed uniqueness constraint.
Likely follow-ups
  • What's the performance difference between First and Single at the SQL level?
  • Should Single always be preferred for queries with a unique index?
Related topics