C#: what's the difference between IEnumerable and IQueryable in EF Core?

poze 4 months ago212 gadeen

4

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>.

Anviwònman:EF Core 8.NET 8

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.

poze 4 months ago

1 Repons

9
✓
✓ Repons yo aksepte

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.

answered 4 months ago

Sign in and verify your email to post an answer.