C#: what's the difference between IEnumerable and IQueryable in EF Core?
poze 4 months ago211 gadeen
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>.
Dyagnostik IA
Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.
1 Repons
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().
Konekte pou di lòt moun si li te mache.
Sign in and verify your email to post an answer.