
IEnumerable vs IQueryable: Where Your EF Core Query Actually Runs
- كاتب موثّق
- EF Core 10
محتويات المقال
.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
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.
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.
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
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
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
Enumerable.Where still filters in C# when it finally runs.
The fix: compose in IQueryable, return finished data
ShopDb with an Orders set:
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();}using Microsoft.EntityFrameworkCore;public sealed class OrderRepository(ShopDb db){ // SQL sent: WHERE, ORDER BY and LIMIT all reach the database public Task<List<Order>> LatestAsync(int customerId, int count, CancellationToken ct) => db.Orders .Where(o => o.CustomerId == customerId) // Queryable.Where, in SQL .OrderByDescending(o => o.CreatedAt) .Take(count) .AsNoTracking() .ToListAsync(ct);}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> | |
|---|---|---|
Where receives | ||
Count() | SELECT COUNT(*) | |
Where |
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
Log the SQL for slow endpoints Turn on command logging in development and look for queries with no WHERE, no paging, or aSELECTof every column for a page that shows three.Find where queries turn into IEnumerable Search data-access code for IEnumerable<T>return types and parameters, forAsEnumerable()andToList()in the middle of a query chain, and for filters stored asFunc<T, bool>.Filter, sort and page before you materialize Keep the chain on IQueryable<T>untilWhere,OrderBy,Skip,TakeandSelectare applied, then callToListAsync. Return the list, or keepIQueryable<T>inside the data layer only.Switch to client evaluation on purpose When 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.WhereandEnumerable.Whereare 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(), anIEnumerable<T>return type and aFunc<T, bool>filter all switch to client evaluation.Lazy isn't translated: deferred Enumerableoperators 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.
التعليقات (0)