๐ญ๐ฌ ๐ฆ๐๐ฒ๐ฝ๐ ๐๐ผ ๐ ๐ฎ๐ธ๐ฒ ๐ฌ๐ผ๐๐ฟ ๐๐ ๐๐ผ๐ฟ๐ฒ ๐ค๐๐ฒ๐ฟ๐ถ๐ฒ๐ ๐ญ๐ฌ๐
๐๐ฎ๐๐๐ฒ๐ฟ
Most .NET developers don't realize this:
EF doesn't limit your query performance โ it's limited by how you use it.
If your API feels slow, your dashboards lag, or queries take seconds to load,
you're likely missing these simple optimizations ๐
๐ญ. ๐๐ฑ๐ฑ ๐๐ฎ๐๐ฎ๐ฏ๐ฎ๐๐ฒ ๐๐ป๐ฑ๐ฒ๐
๐ฒ๐
EF Core doesn't automatically create indexes.
Add them manually for columns used in WHERE, JOIN, and ORDER BY.
โ Use .HasIndex() in your entity configuration.
โ Create a manageable number of indexes
๐ฎ. ๐ข๐ฝ๐๐ถ๐บ๐ถ๐๐ฒ ๐ค๐๐ฒ๐ฟ๐ ๐ฃ๐ฟ๐ผ๐ท๐ฒ๐ฐ๐๐ถ๐ผ๐ป๐
Stop fetching full entities when you only need a few fields.
โ Use .Select() to return only what's required.
โ Smaller payloads = faster materialization and less memory usage.
๐ฏ. ๐จ๐๐ฒ ๐๐๐ก๐ผ๐ง๐ฟ๐ฎ๐ฐ๐ธ๐ถ๐ป๐ด ๐ณ๐ผ๐ฟ ๐ฅ๐ฒ๐ฎ๐ฑ-๐ข๐ป๐น๐ ๐ค๐๐ฒ๐ฟ๐ถ๐ฒ๐
Tracked entities consume memory and CPU.
โ Add .AsNoTracking() for read-only queries.
โ Or set global QueryTrackingBehavior .NoTracking for read-only DbContexts.
๐ฐ. ๐๐ถ๐บ๐ถ๐ ๐ก๐๐บ๐ฏ๐ฒ๐ฟ ๐ผ๐ณ ๐ก๐ฎ๐๐ถ๐ด๐ฎ๐๐ถ๐ผ๐ป๐
Too many .Include() calls can cause N 1 queries or massive joins.
โ Include only what's necessary.
โ Filter includes where possible
๐ฑ. ๐๐๐ผ๐ถ๐ฑ ๐๐ฎ๐ฟ๐ด๐ฒ ๐๐ก / ๐๐ผ๐ป๐๐ฎ๐ถ๐ป๐ ๐๐ถ๐น๐๐ฒ๐ฟ๐
Huge Contains() lists generate slow SQL IN clauses.
โ Fetch IDs in smaller batches.
โ Or store filter data in a temporary table and join it instead.
๐ฒ. ๐จ๐๐ฒ ๐ฃ๐ฎ๐ด๐ถ๐ป๐ฎ๐๐ถ๐ผ๐ป ๐ณ๐ผ๐ฟ ๐๐ฎ๐ฟ๐ด๐ฒ ๐๐ฎ๐๐ฎ๐๐ฒ๐๐
Don't load thousands of records into memory.
โ Use .Skip() and .Take() for offset-based pagination.
โ Or switch to cursor-based pagination โ it's faster and index-friendly.
๐ณ. ๐จ๐๐ฒ ๐๐ผ๐บ๐ฝ๐ถ๐น๐ฒ๐ฑ ๐ค๐๐ฒ๐ฟ๐ถ๐ฒ๐
Frequent queries can be precompiled.
โ Cache LINQ-to-SQL translation with EF .CompileQuery().
โ It's perfect for queries used in loops or called often.
๐ด. ๐จ๐๐ฒ ๐ฆ๐ฝ๐น๐ถ๐๐ค๐๐ฒ๐ฟ๐ ๐๐ผ ๐๐๐ผ๐ถ๐ฑ ๐๐ฎ๐ฟ๐๐ฒ๐๐ถ๐ฎ๐ป ๐๐
๐ฝ๐น๐ผ๐๐ถ๐ผ๐ป
Multiple .Include() joins can cause data duplication.
โ Add .AsSplitQuery() to break large joins into smaller queries.
โ Ideal for complex relationships (Author โ Books โ Publisher).
๐ต. ๐จ๐๐ฒ ๐ฅ๐ฎ๐ ๐ฆ๐ค๐ ๐ณ๐ผ๐ฟ ๐๐ผ๐บ๐ฝ๐น๐ฒ๐
๐ข๐ฝ๐ฒ๐ฟ๐ฎ๐๐ถ๐ผ๐ป๐
Sometimes SQL just wins.
โ For complex filtering, locking, or joins โ use .FromSqlRaw() or .SqlQuery<T>().
โ You get full control over the query plan.
๐ญ๐ฌ. ๐๐ป๐๐ฟ๐ผ๐ฑ๐๐ฐ๐ฒ ๐๐ฎ๐ฐ๐ต๐ถ๐ป๐ด
Don't hit the database for frequently accessed data.
โ Use in-memory cache or Redis.
โ For .NET 9 , try HybridCache โ it solves cache stampede issues.
๐ Bonus Tip:
Measure before optimizing.
Use BenchmarkDotNet, SQL Profiler, or query plans to confirm your bottlenecks.
๐ Join ๐ญ๐ณ,๐ฌ๐ฌ๐ฌ software engineers reading the best EF Core blogs on the market:
antondevtips.com/blog?categoโฆ
โโ
โป๏ธ Repost to help others optimize EF Core
โ Follow me (
@AntonMartyniuk ) to improve your .NET Skills