الانتقال إلى المحتوى
.NETEF Core· 6 دقائق للقراءة

IEnumerable vs IQueryable: Where Your EF Core Query Actually Runs

The same Where compiles against both, but only IQueryable sends it to the database. Once a query becomes IEnumerable, every operator after it runs in memory over rows already fetched.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • EF Core 10
محتويات المقال

An endpoint that shows a customer's ten latest orders is instant in development, where the database holds a few dozen orders. In production it takes seconds, and memory jumps on every call. The code has the filter right there: .Where(o => o.CustomerId == customerId). Then someone turns on SQL logging and finds the query the database actually receives: SELECT ... FROM "Orders". No WHERE, no LIMIT. The filter never left the app.

The common misconception

The belief: IEnumerable<T> and IQueryable<T> are interchangeable. IQueryable<T> is just a more specific IEnumerable<T>, so a repository can return the general one, and a Where added later still ends up in the SQL.

There are good reasons to believe it. IQueryable<T> really does inherit from IEnumerable<T>, so the assignment compiles without a cast. The same operators appear in IntelliSense with the same names. The results are identical, so tests pass. Both are lazy, so it seems EF Core should still see the whole chain before anything runs. And returning the most general interface sounds like good design.

The catch is that "the same operators" are two separate sets of methods, and C# picks one at compile time.

What actually happens

Two Where methods, chosen by the variable's type

Queryable.Where takes an Expression<Func<T, bool>>. For it, the compiler turns your lambda into an : data that describes the code, which EF Core can read and translate into SQL. Enumerable.Where takes a Func<T, bool>, an ordinary compiled delegate that runs in .NET for each item. The compiler chooses by the static type of the expression you call it on, not by the object behind it at runtime. A DbSet<Order> returned as IEnumerable<Order> is still a DbSet, but your code now calls the Enumerable methods.

The SQL is fixed at the last IQueryable

EF Core translates everything up to the point where the query stops being IQueryable<T>. Everything after it is : it runs in memory over whatever the database returned. In a test with EF Core 10 and SQLite, with a table of 10,000 orders and a repository returning IEnumerable<Order>, a filter for one customer, a sort and Take(10) produced SELECT ... FROM "Orders" with no WHERE. EF Core materialized and tracked all 10,000 entities to return 10. The same chain on IQueryable<Order> sent WHERE, ORDER BY and LIMIT, and tracked 10.

AsEnumerable streams, ToList buffers

Both switch to client evaluation, in different ways. ToList() runs the query and loads every row into a list before the next operator runs. AsEnumerable() streams rows one by one, so a later Take(10) stops reading early: in the test, it read 4,172 rows before finding ten matches. The database still ran the unfiltered query, though.

Lazy isn't the same as translated

Both interfaces use , so nothing runs until you enumerate. But being lazy only delays the work; it doesn't move it into the database. A deferred Enumerable.Where still filters in C# when it finally runs.

The fix: compose in IQueryable, return finished data

Both versions use the same ShopDb with an Orders set:

C# OrderRepository.cs
public sealed class OrderRepository(ShopDb db){    // Looks more abstract, but every operator added later runs in memory    public IEnumerable<Order> GetAll() => db.Orders;}public sealed class OrderService(OrderRepository orders){    // SQL sent: SELECT ... FROM "Orders" (no WHERE, no LIMIT)    public List<Order> Latest(int customerId) => orders.GetAll()        .Where(o => o.CustomerId == customerId) // Enumerable.Where, in C#        .OrderByDescending(o => o.CreatedAt)        .Take(10)        .ToList();}

The repository now runs one specific query and returns a List<Order>. The filter, sort and page are built on IQueryable<Order>, so all three reach the database. The caller gets finished data that won't run anything again when it's enumerated.

IQueryable<T>IEnumerable<T>
What Where receivesAn expression treeA compiled delegate
Where the filter runsIn the database, as SQLIn your process, row by row
Rows the database sendsOnly the matching rowsEvery row of the query so far
Count()SELECT COUNT(*)Loads every row, then counts (tested: 10,000 entities)
A C# method in WhereThrows "could not be translated"Runs without complaint

The last row is EF Core protecting you. Since EF Core 3.0, a filter it can't translate throws an InvalidOperationException that tells you to rewrite the query or switch to client evaluation explicitly with AsEnumerable or ToList. Client code is only allowed in the final Select. Switching to IEnumerable<T> doesn't fix such a query; it hides the problem by loading the table.

How to apply it in your project

  1. Log the SQL for slow endpointsTurn on command logging in development and look for queries with no WHERE, no paging, or a SELECT of every column for a page that shows three.
  2. Find where queries turn into IEnumerableSearch data-access code for IEnumerable<T> return types and parameters, for AsEnumerable() and ToList() in the middle of a query chain, and for filters stored as Func<T, bool>.
  3. Filter, sort and page before you materializeKeep the chain on IQueryable<T> until Where, OrderBy, Skip, Take and Select are applied, then call ToListAsync. Return the list, or keep IQueryable<T> inside the data layer only.
  4. Switch to client evaluation on purposeWhen some logic really can't be translated, filter as much as possible in SQL first and call AsEnumerable() only after that. In the test, filtering by customer first left 27 rows for the C# check instead of 10,000.

Key takeaways

  • Queryable.Where and Enumerable.Where are different methods; the variable's static type decides which one runs.
  • EF Core translates the query up to its last IQueryable<T> operator; everything after runs in memory.
  • AsEnumerable(), ToList(), an IEnumerable<T> return type and a Func<T, bool> filter all switch to client evaluation.
  • Lazy isn't translated: deferred Enumerable operators still run in C# over every row the database sends.
  • Compose with IQueryable<T>, check the logged SQL, and return materialized results from the data layer.

📚 المصادر

  1. Client vs. Server Evaluation — EF Core, Microsoft Learn
  2. How Queries Work — EF Core, Microsoft Learn
  3. IQueryable<T> Interface — .NET API, Microsoft Learn
  4. Simple logging — EF Core, Microsoft Learn

التعليقات (0)