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.


🧩 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:

AsNoTracking()

This disables tracking, improving performance — especially for large result sets.


✅ Example

using (var context = new SchoolContext()) { // Normal tracking (slower for read-only) var students = context.Students.ToList(); // Better for read-only queries var readOnlyStudents = context.Students .AsNoTracking() .Where(s => s.IsActive) .ToList(); }

💥 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

using Microsoft.EntityFrameworkCore; public class StudentQueries { // Create a compiled query private static readonly Func<SchoolContext, int, Student?> _getStudentById = EF.CompileQuery((SchoolContext context, int id) => context.Students.FirstOrDefault(s => s.Id == id)); public static Student? GetStudentById(SchoolContext context, int id) { // Use the compiled query (faster) return _getStudentById(context, id); } } // Usage: using (var context = new SchoolContext()) { var student = StudentQueries.GetStudentById(context, 1); }

💥 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:

Install-Package EFCore.BulkExtensions

Then:

using (var context = new SchoolContext()) { var students = context.Students.Where(s => s.IsGraduated == false).ToList(); // Update in batch students.ForEach(s => s.IsGraduated = true); context.BulkUpdate(students); }

💥 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:

protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Student>() .HasIndex(s => s.Email) .IsUnique(); // optional }

Using Data Annotations:

[Index(nameof(Email), IsUnique = true)] public class Student { public int Id { get; set; } public string Email { get; set; } = ""; }

Now, when EF runs migrations, it automatically creates indexes in your SQL database.


💥 Benefit:

  • Faster WHERE, ORDER BY, and JOIN queries

  • Greatly improves performance for frequently filtered columns


⚡ Summary Table

Optimization TechniqueUse CaseKey Benefit
AsNoTracking()Read-only queriesFaster, low memory
Compiled QueriesRepeated queriesAvoid SQL re-translation
Batch OperationsBulk insert/update/deleteReduce DB calls
Proper IndexingFrequent lookups or joinsFaster data access

Comments

Popular posts from this blog

.NET Core Interview Questions and Answers for 10+ Years Experienced Professionals

What are SOLID Principles?

.NET Core Senior Interview Q&A