important performance optimization techniques in Entity Framework (EF Core) when working with databases in C#.
Use AsNoTracking for read-only queries.
Compiled Queries.
Batch operations.
Proper indexing.
Use AsNoTracking for read-only queries.
Compiled Queries.
Batch operations.
Proper indexing.
🧩 1️⃣ Use AsNoTracking() for Read-Only Queries
💡 Concept
By default, Entity Framework Core tracks all the entities you retrieve — meaning it keeps them in the change tracker to detect modifications and update them later when you call SaveChanges().
This tracking consumes memory and processing time.
If you only need to read data (not modify or update it), you should use:
This disables tracking, improving performance — especially for large result sets.
✅ Example
💥 Benefit:
-
Faster query execution
-
Lower memory usage
-
Ideal for reporting, listing, or exporting data
🧮 2️⃣ Compiled Queries
💡 Concept
When EF executes a LINQ query, it first translates it into SQL, which takes time.
If the same query runs many times (like inside loops or in high-traffic APIs), that translation cost adds up.
To fix that, EF lets you pre-compile the query so SQL generation happens only once, and EF reuses it later.
✅ Example
💥 Benefit:
-
Avoids repeated SQL translation
-
Significant performance boost for queries that run very frequently
⚙️ 3️⃣ Batch Operations
💡 Concept
By default, EF sends one SQL statement per entity (like insert/update/delete).
For example, updating 1000 records sends 1000 SQL commands, which is slow.
Batch operations combine multiple operations into a single SQL command, greatly improving performance.
✅ Example Using EFCore.BulkExtensions
Install NuGet package:
Then:
💥 Benefit:
-
10x–100x faster for large updates/inserts/deletes
-
Reduces round-trips to the database
🗃️ 4️⃣ Proper Indexing
💡 Concept
Indexes in a database work like an index in a book — they make searching faster.
Without indexes, the database scans every row (full table scan), which is slow for large tables.
✅ Example (Code-First with EF Core)
You can define indexes using Fluent API or Data Annotations.
Using Fluent API:
Using Data Annotations:
Now, when EF runs migrations, it automatically creates indexes in your SQL database.
💥 Benefit:
-
Faster
WHERE,ORDER BY, andJOINqueries -
Greatly improves performance for frequently filtered columns
⚡ Summary Table
| Optimization Technique | Use Case | Key Benefit |
|---|---|---|
| AsNoTracking() | Read-only queries | Faster, low memory |
| Compiled Queries | Repeated queries | Avoid SQL re-translation |
| Batch Operations | Bulk insert/update/delete | Reduce DB calls |
| Proper Indexing | Frequent lookups or joins | Faster data access |
Comments
Post a Comment