C#: what's the difference between IEnumerable and IQueryable in EF Core?
asked 4 months ago213 viewsen
My query loads the entire Orders table into memory before filtering, even though I wrote .Where(). The code passes the DbSet through a method that takes IEnumerable<Order>.
AI diagnosis
AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.
1 Answer
That's exactly the problem:
- IQueryable<T> builds an expression tree. EF translates .Where, .OrderBy and .Take to SQL and runs it in the database. - IEnumerable<T>: once the query is typed as this, subsequent LINQ runs in memory (LINQ to Objects). EF runs SELECT * FROM Orders and filters in C#.
// ❌ filters in memory
IEnumerable<Order> Recent(IEnumerable<Order> src) => src.Where(o => o.Date > cutoff);
// ✅ filters in SQL
IQueryable<Order> Recent(IQueryable<Order> src) => src.Where(o => o.Date > cutoff);
Keep queries as IQueryable until the final ToListAsync(). To see the generated SQL, log it (optionsBuilder.LogTo(Console.WriteLine)) or call query.ToQueryString().
Sign in to tell others whether this worked.
Sign in and verify your email to post an answer.