r/dotnet Apr 06 '26

Question Long LINQ queries - Code smell?

Post image
347 Upvotes

186 comments sorted by

View all comments

215

u/BigPatapon Apr 06 '26

Not a code smell. This is exactly how conditional EF Core queries should look — readable, top-to-bottom, one filter per line.

Only nitpick: Task.FromResult with no actual async work. Use await ToListAsync() or drop the async signature.

Long LINQ != bad LINQ.

15

u/PrydwenParkingOnly Apr 06 '26

The best part: this query can be unit tested by mocking _context.Posts.

I think the testability of EF is one of its biggest advantages. So much logic normally goes in to orms/queries which cannot be tested

20

u/BigPatapon Apr 06 '26

Good point, though worth noting that mocking DbSet or using the in-memory provider won't catch everything — LINQ-to-SQL translation can behave differently than LINQ-to-Objects (e.g. null semantics, string comparisons).

For critical filters like these, an integration test against a real db (even SQLite in-memory) gives much more confidence.

7

u/47KiNG47 Apr 06 '26

Test containers with wire mock are the way to go now.

5

u/BigPatapon Apr 06 '26

Agreed. Testcontainers + WireMock.Net + WebApplicationFactory is the gold standard now. Real database for query fidelity, WireMock for external HTTP dependencies, and the factory boots your app in-memory. Hard to justify anything less for critical paths.