Introduction
Writing the correct filter is only part of writing a correct Entity Framework Core query. The LINQ method used at the end of the query directly affects application behavior, possible exceptions and the cost of the SQL sent to the database. In particular, First, FirstOrDefault, Single, SingleOrDefault, Any and Count may look similar, but they express different requirements.
This lesson separates three common scenarios: retrieving a record, checking whether a record exists and calculating the number of records. We will first examine result semantics, then demonstrate incorrect uses that produce exceptions or unnecessary work. Finally, we will implement clear asynchronous service methods for EF Core 10 and .NET 10.
Sample model and query context
Assume that an order management application contains the following Customer and Order entities:
public class Customer
{
public int Id { get; set; }
public string Email { get; set; } = null!;
public bool IsActive { get; set; }
public ICollection<Order> Orders { get; set; } = new List<Order>();
}
public class Order
{
public int Id { get; set; }
public int CustomerId { get; set; }
public string OrderNumber { get; set; } = null!;
public decimal Total { get; set; }
public Customer Customer { get; set; } = null!;
}Assume that an email address must be unique according to the business rules. That rule should be enforced not only in application code, but also in the database with a unique index. This protects the assumption behind Single and SingleOrDefault.
First and FirstOrDefault: retrieving the first match
First returns the first record matching the predicate. If no record exists, it throws InvalidOperationException. It can be appropriate when the record is guaranteed to exist, but that assumption is often unsafe for identifiers or search terms supplied by users.
var order = await db.Orders
.Where(o => o.OrderNumber == orderNumber)
.FirstAsync();If the order does not exist, this code throws an exception. In an API endpoint, that can accidentally become a 500 response instead of a 404 response. When absence is a normal outcome, use FirstOrDefaultAsync:
var order = await db.Orders
.FirstOrDefaultAsync(o => o.OrderNumber == orderNumber);
if (order is null)
{
return NotFound();
}The First family does not treat multiple matches as an error. It returns one matching record. If the selected record matters, always specify an ordering:
var latestOrder = await db.Orders
.Where(o => o.CustomerId == customerId)
.OrderByDescending(o => o.Id)
.FirstOrDefaultAsync();Common mistake: using First without ordering
The following code may run successfully, but it does not reliably mean “the latest order”:
var latestOrder = await db.Orders
.Where(o => o.CustomerId == customerId)
.FirstOrDefaultAsync();Physical insertion order is not a reliable ordering guarantee for a relational query. Ordering the result according to the business rule makes the behavior both correct and explicit.
Single and SingleOrDefault: validating uniqueness
Single requires exactly one matching record. It throws when there are no matches and also when there is more than one match. SingleOrDefault returns the default value, usually null for a reference type, when there are no matches; it still throws when multiple matches exist.
var customer = await db.Customers
.SingleOrDefaultAsync(c => c.Email == email);This query expresses that an email address should identify at most one customer. If duplicate data exists, exposing the problem is usually safer than silently selecting an arbitrary customer.
Developers sometimes use SingleOrDefault as if it were a safer version of FirstOrDefault. That is incorrect. SingleOrDefault deliberately reports a second match as an error. If multiple records are valid and any one of them is acceptable, use FirstOrDefault, preferably with an explicit ordering. If at most one record is valid, use SingleOrDefault.
When Single is the wrong choice
var activeOrder = await db.Orders
.SingleAsync(o => o.CustomerId == customerId && o.Status == OrderStatus.Active);If a customer may have several active orders, this query is incorrect. It will throw as soon as a second active order is added. If the requirement is simply to retrieve one active order, use an explicit ordering and FirstOrDefaultAsync:
var activeOrder = await db.Orders
.Where(o => o.CustomerId == customerId && o.Status == OrderStatus.Active)
.OrderByDescending(o => o.Id)
.FirstOrDefaultAsync();If the business rule truly allows only one active order, SingleAsync is appropriate, but the database should enforce the same rule with a unique constraint or filtered index. Relying only on a LINQ method does not prevent race conditions or data inserted outside the application.
Any: the correct choice for existence checks
Use Any when you only need to know whether at least one matching record exists. It returns a boolean and does not materialize an entity or calculate a total.
var hasPendingOrders = await db.Orders
.AnyAsync(o => o.CustomerId == customerId && o.Status == OrderStatus.Pending);The following approach is unnecessary when only a boolean is needed:
var pendingCount = await db.Orders
.CountAsync(o => o.CustomerId == customerId && o.Status == OrderStatus.Pending);
var hasPendingOrders = pendingCount > 0;CountAsync is intended for cases where the numeric total is required. For an existence check, AnyAsync communicates the intent more accurately and can commonly be translated by the provider into an EXISTS-style query. The database may then stop searching after finding the first qualifying row.
Count: use it when the number is required
Use CountAsync when a screen, report or business rule genuinely needs the total number of records:
var orderCount = await db.Orders
.CountAsync(o => o.CustomerId == customerId);Using Count only to determine whether the value is greater than zero can perform more work than necessary. An index on the filtered columns can improve performance, but choosing the correct result operator is still important.
Keep the following requirements separate:
- “Does at least one record exist?” Use
AnyAsync. - “How many records exist?” Use
CountAsync. - “Must there be exactly one record?” Use
SingleAsyncorSingleOrDefaultAsync. - “Which matching record should I retrieve first?” Use
FirstAsyncorFirstOrDefaultAsyncwith explicit ordering.
Comparing result semantics
| Method | No results | Multiple results | Suitable scenario |
|---|---|---|---|
First | Throws | Returns the first | A record is guaranteed to exist |
FirstOrDefault | Default or null | Returns the first | No match is a normal outcome |
Single | Throws | Throws | Exactly one record is required |
SingleOrDefault | Default or null | Throws | At most one record is expected |
Any | false | true | Existence checks |
Count | 0 | Returns the total | The numeric total is required |
Designing asynchronous service methods
EF Core queries perform database I/O, so asynchronous methods are generally preferred in web applications. Where and OrderBy only build the expression tree and therefore do not have asynchronous versions. Execution methods such as FirstAsync, SingleOrDefaultAsync, AnyAsync and CountAsync do.
public sealed class OrderQueryService(AppDbContext db)
{
public Task<bool> HasPendingOrdersAsync(int customerId, CancellationToken cancellationToken)
=> db.Orders.AnyAsync(
o => o.CustomerId == customerId && o.Status == OrderStatus.Pending,
cancellationToken);
public Task<int> CountOrdersAsync(int customerId, CancellationToken cancellationToken)
=> db.Orders.CountAsync(o => o.CustomerId == customerId, cancellationToken);
public Task<Order?> FindByNumberAsync(string orderNumber, CancellationToken cancellationToken)
=> db.Orders.FirstOrDefaultAsync(o => o.OrderNumber == orderNumber, cancellationToken);
public Task<Customer?> FindCustomerByEmailAsync(string email, CancellationToken cancellationToken)
=> db.Customers.SingleOrDefaultAsync(c => c.Email == email, cancellationToken);
}Each method name and return type makes the intended semantics visible. Passing a CancellationToken can also stop unnecessary database work when a request is cancelled.
Inspecting generated SQL and performance
A theoretically appropriate operator is not a substitute for measuring real queries. During development, ToQueryString can help inspect the SQL generated by EF Core:
var query = db.Orders
.Where(o => o.CustomerId == customerId)
.OrderByDescending(o => o.Id)
.Take(1);
var sql = query.ToQueryString();In production, monitor command duration and database activity without logging sensitive values. The exact difference between Any and Count depends on the provider, query shape, indexes and data volume. Always test with the actual database engine and representative data.
Frequent mistakes
- Using Single for every lookup: It creates unexpected exceptions when uniqueness is not a real business rule.
- Using First when absence is possible: A normal 404 case may become an application error.
- Using Count instead of Any: It calculates a total that is not needed for an existence check.
- Using First without ordering: It leaves the meaning of “first” undefined.
- Using SingleOrDefault without enforcing uniqueness: The method exposes duplicate data, but a database constraint is still needed to prevent it.
- Calling ToList before First or Count: It loads all matching rows into memory unnecessarily. Keep the operation on the database.
Practice exercise
Choose the correct operator and implement each scenario asynchronously:
- A missing
OrderNumbershould result in a 404 response. - An email address should identify at most one customer, and duplicate data should be treated as an error.
- Check whether a customer has any pending orders.
- Display the total number of orders for a customer on an administration screen.
- Retrieve the most recently created order for a customer.
Test no-result, one-result and multiple-result cases separately. For SingleOrDefaultAsync, deliberately create duplicate data in a test database and verify that the integrity problem is observable. Also inspect the generated SQL and confirm that Any, rather than Count, is used when only existence matters.
Conclusion
The distinction between First, Single, Any and Count is not merely syntactic. Each method communicates a different business rule and result expectation. FirstOrDefault treats absence as a normal outcome, while SingleOrDefault treats multiple matches as a data-integrity problem. Any is the right tool for existence checks, and Count should be reserved for cases where the actual total is needed.
Choosing the correct operator makes exception behavior predictable, reduces unnecessary work and clarifies the intent of the code. In production systems, evaluate this choice together with business rules, database constraints, indexes, generated SQL and measurements from realistic data.
Sources
- https://learn.microsoft.com/en-us/ef/core/querying/
- https://learn.microsoft.com/en-us/ef/core/performance/efficient-querying
- https://learn.microsoft.com/en-us/ef/core/miscellaneous/async
- https://learn.microsoft.com/en-us/dotnet/api/system.linq.queryable.any?view=net-10.0
- https://learn.microsoft.com/en-us/dotnet/api/system.linq.queryable.singleordefault?view=net-10.0
- https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.firstordefault?view=net-10.0