C#: what's the difference between IEnumerable and IQueryable in EF Core?
posée 4 months ago215 vuesen
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>.
Diagnostic IA
Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.
1 réponse
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().
Connectez-vous pour dire si ça a marché.
Sign in and verify your email to post an answer.