📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

In EF Core, what is the practical difference between IQueryable<T> and IEnumerable<T>? Where does a Where filter actually run in each case, and what goes wrong when someone calls AsEnumerable() or returns IEnumerable<T> from a repository too early?

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.

Junior Theory Beginner ef-core ienumerable iqueryable linq querying sql-server

🎯 Key points

  • DbSet<T> is IQueryable<T>: operators build an expression tree, no SQL runs yet
  • Queryable.Where takes Expression<Func<T,bool>>; Enumerable.Where takes Func<T,bool>
  • The static (compile-time) type picks the overload, not the runtime type
  • AsEnumerable() is only a cast (runs on enumeration); ToList() executes immediately; either way later operators run in memory
  • A repository returning IEnumerable<T> turns later filters into full-table reads
  • Compose IQueryable inside the data layer, return materialised DTOs across layer boundaries
  • Check the SQL with ToQueryString() or LogTo before trusting a query
  • Use AsEnumerable() deliberately only for the final, untranslatable step

⏱ 30-second answer

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.

  • The compile-time type decides which 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.

🗣 Full answer (senior)

How I would answer this in an interview

"With EF Core the difference is where the work happens. A DbSet<Order> is an IQueryable<Order>. When I chain Where, OrderBy and Take on it, nothing runs: each call goes to Queryable.Where, which takes an Expression<Func<Order,bool>> and adds a node to an expression tree. When I finally call ToListAsync(), EF Core translates the whole tree into one SQL statement, so the filter becomes a WHERE clause and the Take becomes TOP or OFFSET/FETCH. SQL Server does the filtering and can use an index.

IEnumerable<T> binds to Enumerable.Where, which takes a compiled Func<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 return IEnumerable<Order>, even though the object underneath is still an EF query, the caller's .Where(o => o.Total > 100) is Enumerable.Where. EF Core runs SELECT * FROM Orders with no filter, streams every row, builds every entity, and C# throws most of them away.

The mistake I see is AsEnumerable() or ToList() 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 as IQueryable until the last operator, check the SQL with ToQueryString(), and use AsEnumerable() only on purpose, for a final step SQL genuinely can't do, after the rows are already filtered."


The two interfaces side by side

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

Where the switch happens without you noticing

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#

When to use each

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

Production example

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].

🔍 What the interviewer is checking

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

  • Mentions expression trees versus delegates.
  • Says the compile-time type decides, with the repository example.
  • Knows AsEnumerable() is a cast and what runs after it.
  • Verifies with ToQueryString() or SQL logging.

Red flags

  • "IQueryable is faster" with no mechanism.
  • Thinks AsEnumerable() runs the query or is always fine.
  • Never checks generated SQL.

📚 Learn in depth

1. Two families of extension methods

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.

2. What the lambda becomes

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.

3. The EF Core pipeline

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.

4. AsEnumerable() is just a cast

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.

5. Client evaluation is limited since EF Core 3.0

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.

6. Repositories and layering

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.

Try it yourself

  1. Write db.Orders.Where(o => o.Total > 100).Take(5) and call ToQueryString(). Then insert .AsEnumerable() before Where and compare what LogTo(Console.WriteLine) shows.
  2. Declare IEnumerable<Order> q = db.Orders; then q.Where(...).ToList() and confirm in the log that the SQL has no WHERE.
  3. Seed 200,000 rows and use BenchmarkDotNet to compare the two versions: time and allocated bytes.
  4. Put a C# method (IsVip(o)) inside a Where and read the translation exception. Then move it into the final Select and see that it runs.
  5. Hover over .Where in your IDE for both variables and note which class (Queryable or Enumerable) it binds to.

💻 Code

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]

⚠ Common mistakes

  • Mistake: Returning 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.
  • Mistake: Adding 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.
  • Mistake: Believing 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.
  • Mistake: Assuming the runtime type decides. Why it is wrong: overload resolution is compile-time, so IEnumerable<T> q = db.Orders loses translation. Instead: use var or IQueryable<T> for queries you will keep composing.
  • Mistake: Testing only against a tiny local database. Why it is wrong: a full read of 50 rows is invisible. Instead: inspect SQL with 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.
  • Mistake: Calling .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.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions Expression, Provider or expression trees. Why: Checks the deeper IQueryable contract and whether a repository should expose IQueryable.
    How to answer

    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.

  2. When: Candidate says the lambda becomes an expression tree. Why: Checks how the compiler builds expression trees and what cannot appear in them.
    How to answer

    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.

  3. When: Candidate mentions the AsEnumerable() workaround. Why: Checks the candidate rewrites predicates rather than hiding translation failures.
    How to answer

    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().

↩ Usually asked after

More in Querying

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me