Covers where EF Core queries execute depending on IQueryable versus IEnumerable, how the static type decides SQL versus in-memory filtering, and the AsEnumerable() and early-materialisation traps.
With EF Core, IQueryable<T> means "a query not yet sent": each LINQ operator adds to an expression tree, and the provider translates the whole tree into one SQL statement when you enumerate it. IEnumerable<T> means "objects in memory": operators are compiled delegates that run in your process over rows already fetched.
Where you get: Queryable.Where(Expression<...>) or Enumerable.Where(Func<...>).AsEnumerable() is only a cast and ToList() runs the query straight away, but after either one (or a method that returns IEnumerable<T>) every later filter, sort and Take runs in C#. The SQL that is sent no longer contains them, so the database can't use an index or TOP, and far more rows cross the wire.The trade-off: keep it IQueryable while the database can do the work, and switch to memory only for the last step SQL can't do.
"With EF Core the difference is where the work happens. A
DbSet<Order>is anIQueryable<Order>. When I chainWhere,OrderByandTakeon it, nothing runs: each call goes toQueryable.Where, which takes anExpression<Func<Order,bool>>and adds a node to an expression tree. When I finally callToListAsync(), EF Core translates the whole tree into one SQL statement, so the filter becomes aWHEREclause and theTakebecomesTOPorOFFSET/FETCH. SQL Server does the filtering and can use an index.
IEnumerable<T>binds toEnumerable.Where, which takes a compiledFunc<Order,bool>. It runs in my process over objects that already exist. The important part is that C# picks the overload from the static type of the variable. If a repository method is declared to returnIEnumerable<Order>, even though the object underneath is still an EF query, the caller's.Where(o => o.Total > 100)isEnumerable.Where. EF Core runsSELECT * FROM Orderswith no filter, streams every row, builds every entity, and C# throws most of them away.The mistake I see is
AsEnumerable()orToList()put in early "to make it work" after a translation error. It does make the exception go away, by moving everything after it into memory. On a 20-row dev database nobody notices; on a 5-million-row production table it is a timeout. So I keep queries asIQueryableuntil the last operator, check the SQL withToQueryString(), and useAsEnumerable()only on purpose, for a final step SQL genuinely can't do, after the rows are already filtered."
IQueryable<T> (EF Core) |
IEnumerable<T> |
|
|---|---|---|
| Operator signature | Expression<Func<T,bool>> |
Func<T,bool> |
| What the operator does | Adds a node to an expression tree | Wraps an iterator around a delegate |
| Executes | When enumerated, as one SQL statement | In memory, row by row |
| Filter runs on | SQL Server (indexes, TOP) |
Your app server's CPU |
| Data transferred | Only matching rows and columns | Everything the source produced |
| Can call any C# method | No, only what the provider translates | Yes |
| Code | Effect |
|---|---|
IEnumerable<Order> GetOrders() => db.Orders; |
Caller's filters run in memory |
db.Orders.AsEnumerable().Where(...) |
Full table read, filter in C# |
db.Orders.ToList().Where(...) |
Same, plus a full list allocation |
db.Orders.Where(...).AsEnumerable().Select(Format) |
Fine: filtered in SQL, formatted in C# |
Use IQueryable |
Use IEnumerable / AsEnumerable() |
|---|---|
| Filtering, sorting, paging, aggregating | Formatting or calling a C# method on the final, already-small result |
Projection to a DTO with Select |
Logic that has no SQL equivalent, after the rows are reduced |
| Composing a query across layers inside the data layer | Returning results to callers outside the data layer |
A search endpoint returned IEnumerable<Customer> from a repository and the controller applied .Where(c => c.Region == region).Take(20). The SQL had no WHERE; each call read about [400,000] rows and took around [3 s] with [~250 MB] allocated. Changing the return type to IQueryable<Customer> inside the data layer (and projecting to a DTO) brought it to [one indexed query of ~15 ms].
Checks that the candidate knows the static type chooses Queryable or Enumerable operators, and can spot a query that silently reads a whole table.
Green flags
AsEnumerable() is a cast and what runs after it.ToQueryString() or SQL logging.Red flags
AsEnumerable() runs the query or is always fine.System.Linq has two parallel static classes:
Enumerable.Where<T>(this IEnumerable<T> source, Func<T,bool> predicate)
Queryable.Where<T>(this IQueryable<T> source, Expression<Func<T,bool>> predicate)
IQueryable<T> inherits from IEnumerable<T>, so both apply. The compiler's overload resolution prefers the more specific receiver type, IQueryable<T>, but only if the static type of the expression is IQueryable<T>. Overload resolution happens at compile time; the runtime type never matters.
The same lambda text compiles to different things:
o => o.Total > 100
as Func<Order,bool> -> IL method (a delegate)
as Expression<Func<Order,bool>> -> code that builds a tree:
Lambda
└ GreaterThan
├ Member(o.Total)
└ Constant(100)
A delegate can only be executed. A tree can be inspected, which is what lets EF Core turn it into WHERE [o].[Total] > 100.0.
db.Orders.Where(...).OrderBy(...).Take(20)
│ (each call: Queryable method -> provider.CreateQuery -> bigger tree)
▼
ToListAsync() -> provider.ExecuteAsync(tree)
▼
Query compilation (cached by tree shape):
preprocessing -> translation to a SQL tree -> SQL generation
▼
DbCommand -> SQL Server -> DbDataReader -> materialiser -> entities
EF Core caches the compiled query keyed by the tree's shape, and captured variables become SQL parameters, so o.Total > minTotal is one cached plan whatever minTotal is.
AsEnumerable() returns the same object typed as IEnumerable<T>. It does not run anything. But every operator after it now binds to Enumerable, so when you enumerate:
db.Orders.AsEnumerable().Where(o => o.Total > 100).Take(20)
SQL: SELECT [o].[Id], [o].[CustomerId], [o].[Total], ... FROM [Orders] AS [o]
C#: iterate all rows, materialise each entity, test Total, stop after 20 matches
Because it streams, Take(20) may stop early, but you still pay for every row read before the 20th match, and with tracking every entity read is added to the change tracker.
EF Core 1–2 silently evaluated untranslatable parts on the client. Since 3.0, only the final Select may contain untranslatable code; anything else throws InvalidOperationException: The LINQ expression ... could not be translated. That exception is the reason people reach for AsEnumerable(). The right fix is usually to rewrite the predicate in translatable terms, not to move the whole query to memory.
Returning IQueryable<T> from a repository lets callers compose queries, but it leaks EF Core semantics (translation failures, a live DbContext) into upper layers. Returning IEnumerable<T> hides that but forces you to filter inside the repository. The common middle ground: compose IQueryable inside the data layer (or with specifications), and return materialised List<TDto> or IReadOnlyList<TDto> to callers.
db.Orders.Where(o => o.Total > 100).Take(5) and call ToQueryString(). Then insert .AsEnumerable() before Where and compare what LogTo(Console.WriteLine) shows.IEnumerable<Order> q = db.Orders; then q.Where(...).ToList() and confirm in the log that the SQL has no WHERE.IsVip(o)) inside a Where and read the translation exception. Then move it into the final Select and see that it runs..Where in your IDE for both variables and note which class (Queryable or Enumerable) it binds to.The static type decides whether the filter becomes SQL; the comments show the SQL EF Core sends.
namespace Shop.Data;
using Microsoft.EntityFrameworkCore;
public sealed record OrderSummary(int Id, decimal Total);
public sealed class OrderQueries(ShopDbContext db)
{
// GOOD: stays IQueryable until ToListAsync, so WHERE, ORDER BY and TOP run in SQL Server.
public Task<List<OrderSummary>> GetLargeOrdersAsync(decimal minTotal, CancellationToken ct) =>
db.Orders
.Where(o => o.Total >= minTotal) // Queryable.Where -> WHERE [o].[Total] >= @minTotal
.OrderByDescending(o => o.Total)
.Take(20) // TOP(@p)
.Select(o => new OrderSummary(o.Id, o.Total))
.ToListAsync(ct);
// BAD: the return type is IEnumerable, so callers' filters bind to Enumerable.Where.
public IEnumerable<Order> AllOrders() => db.Orders;
// GOOD use of AsEnumerable: filter and project in SQL first, then call C# that cannot translate.
public async Task<List<string>> GetLabelsAsync(int customerId, CancellationToken ct)
{
var rows = await db.Orders
.Where(o => o.CustomerId == customerId)
.Select(o => new { o.Id, o.Total, o.PlacedAt })
.ToListAsync(ct); // small, filtered result
return rows.Select(r => LabelFormatter.Format(r.Id, r.Total, r.PlacedAt)).ToList();
}
}
public static class LabelFormatter
{
public static string Format(int id, decimal total, DateTimeOffset placedAt) =>
$"#{id} {total:C} {placedAt:dd/MM/yyyy}";
}
// Caller: looks identical, behaves completely differently.
var fast = db.Orders.Where(o => o.Total > 1000).Take(10).ToList(); // filtered in SQL
var slow = queries.AllOrders().Where(o => o.Total > 1000).Take(10).ToList(); // full table read
-- fast
SELECT TOP(@p) [o].[Id], [o].[CustomerId], [o].[PlacedAt], [o].[Total]
FROM [Orders] AS [o]
WHERE [o].[Total] > 1000.0
-- slow
SELECT [o].[Id], [o].[CustomerId], [o].[PlacedAt], [o].[Total]
FROM [Orders] AS [o]
IEnumerable<T> from a repository and filtering in the caller. Why it is wrong: the caller's Where binds to Enumerable.Where, so SQL has no WHERE and every row is read. Instead: filter inside the data layer, or compose IQueryable there and return a materialised list.AsEnumerable() or ToList() to silence a translation exception. Why it is wrong: everything after it runs in memory over the whole table, costing memory (every entity materialised, and tracked if tracking is on) and CPU on the web server. Instead: rewrite the predicate in translatable form (e.g. EF.Functions.Like, a computed column) and keep client code in the final projection.AsEnumerable() executes the query. Why it is wrong: it is only a cast; execution starts on enumeration (unlike ToList(), which executes immediately). Instead: know that it changes which operators bind, not when SQL runs.IEnumerable<T> q = db.Orders loses translation. Instead: use var or IQueryable<T> for queries you will keep composing.ToQueryString() or logging in code review, run integration tests against SQL Server (Testcontainers) with production-like volumes, and watch rows read and allocations with BenchmarkDotNet or Application Insights before release..Count() on an IEnumerable that wraps a query. Why it is wrong: it enumerates every row instead of sending SELECT COUNT(*). Instead: call CountAsync() on the IQueryable.The senior point is that IQueryable versus IEnumerable is a boundary decision, not a syntax detail. Exposing IQueryable everywhere gives callers power and lets translation errors surface far from the data layer; hiding it behind IEnumerable is safe only if the filtering already happened. I keep composition inside the data layer and return small, materialised DTO lists.
I also treat AsEnumerable() as a code-review flag: each one needs a comment saying why the rows before it are already few.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
Return IQueryable<T> from data layer |
Internal query composition, specifications | Translation errors appear in callers; context must stay alive | Public service or API boundaries |
Return List<TDto> / IReadOnlyList<TDto> |
Most application services | Data layer must take filter/paging parameters | When callers truly need arbitrary composition (e.g. OData) |
AsEnumerable() mid-query |
Final untranslatable step on a filtered set | Rows before it are all transferred | Before any filter, sort or paging |
IQueryable<T> is an IEnumerable<T> that also carries an expression tree and a provider. Queryable.Where takes an Expression<Func<T,bool>> and just wraps the expression, and when you enumerate, the provider, for example EF Core, translates the whole tree, typically into SQL. IEnumerable operators take delegates and run in memory. Which one you get depends on the static type of the variable, so storing a DbSet in an IEnumerable variable quietly moves every later Where into memory. AsEnumerable() does that on purpose. I keep IQueryable inside the data layer and return materialised results.
An expression tree is code represented as data. If you assign a lambda to Expression<Func<Order,bool>>, the compiler builds an object tree of parameter, member, binary and constant nodes instead of IL, and that is what lets EF Core read your Where and turn it into SQL. You can build trees with the Expression factory methods, rewrite them with ExpressionVisitor, and turn them into delegates with Compile(). Compiling is expensive, so cache the result, and under Native AOT it falls back to a slower interpreter. Only expression-bodied lambdas qualify, and features like ?., tuple literals and switch expressions are not allowed.
Read the message: it names the sub-expression EF Core couldn't translate (usually a C# method, an unmapped property or a complex string operation). Then rewrite that part in SQL-compatible terms: simpler LINQ with plain operators and ranges, EF.Functions.Like, built-in mapped methods, a mapped computed column, or a database function mapped with HasDbFunction. Since EF Core 3.0, client code is allowed only in the final Select; anything you place after AsEnumerable() also runs in memory, so do that only after the filters have run in SQL. Confirm the fix with ToQueryString().
Last updated 23 Nov 2026.