C# tutorials > Frameworks and Libraries > Entity Framework Core (EF Core) > Performance optimization in EF Core (no-tracking queries, compiled queries, indexing)
Performance optimization in EF Core (no-tracking queries, compiled queries, indexing)
Introduction to Performance Optimization in EF Core
No-Tracking Queries: Disabling Change Tracking
AsNoTracking()
method disables this change tracking. This is especially beneficial for read-only operations like displaying data on a webpage or generating reports.
csharp
using Microsoft.EntityFrameworkCore;
using System.Linq;
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("YourConnectionString");
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
public class Example
{
public void GetBlogsNoTracking()
{
using (var context = new BloggingContext())
{
var blogs = context.Blogs
.AsNoTracking()
.ToList();
// Blogs are retrieved without change tracking.
}
}
}
Concepts Behind No-Tracking Queries
SaveChanges()
is called. This tracking mechanism consumes memory and CPU cycles. By disabling tracking with AsNoTracking()
, we eliminate this overhead, resulting in faster query execution and reduced memory consumption.
Real-Life Use Case for No-Tracking Queries
AsNoTracking()
when fetching product data for the listing page significantly improves performance, especially when dealing with a large number of products. It reduces the load on the database server and speeds up page load times for users.
Best Practices for No-Tracking Queries
AsNoTracking()
for read-only scenarios.AsNoTracking()
when you need to modify entities retrieved from the database. Modifying a non-tracked entity and then trying to update it will result in unexpected behavior.Select
) along with AsNoTracking()
to retrieve only the necessary columns. This further reduces the amount of data transferred and processed.
Interview Tip - No-Tracking Queries
When to Use No-Tracking Queries
Memory Footprint of No-Tracking Queries
Compiled Queries: Pre-compiling Query Execution Plans
EF.CompileQuery
method is used to create a compiled query.
csharp
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Query;
using System.Linq;
using System;
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("YourConnectionString");
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
public class Example
{
private static readonly Func<BloggingContext, int, Blog> _compiledQuery =
EF.CompileQuery((BloggingContext context, int blogId) =>
context.Blogs
.FirstOrDefault(b => b.BlogId == blogId));
public void GetBlogByIdCompiled(int id)
{
using (var context = new BloggingContext())
{
var blog = _compiledQuery(context, id);
// Blog retrieved using compiled query.
}
}
}
Concepts Behind Compiled Queries
Real-Life Use Case for Compiled Queries
Alternatives to Compiled Queries (EF Core 7+)
Best Practices for Compiled Queries
Interview Tip - Compiled Queries
When to Use Compiled Queries
Pros of Compiled Queries
Cons of Compiled Queries
Indexing: Optimizing Data Retrieval
HasIndex
method in the OnModelCreating
method.
csharp
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("YourConnectionString");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.HasIndex(b => b.Url);
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
Concepts Behind Indexing
Real-Life Use Case for Indexing
Best Practices for Indexing
WHERE
clauses.WHERE
clause.INSERT
, UPDATE
, DELETE
) because the database has to update the indexes as well as the table data.
Interview Tip - Indexing
When to Use Indexing
WHERE
clauses.
Cons of Indexing
FAQ
-
When should I use `AsNoTracking()`?
UseAsNoTracking()
when you only need to read data from the database and don't intend to update or delete any entities. This is common for displaying data or generating reports. -
What are compiled queries in EF Core?
Compiled queries are pre-compiled LINQ queries that EF Core stores in a cache. This avoids the overhead of repeatedly compiling the same query each time it's executed. -
How do indexes improve performance?
Indexes speed up data retrieval by creating a data structure that allows the database to quickly locate relevant rows without scanning the entire table. -
Are Compiled Queries still necessary with EF Core 7 and above?
With EF Core 7, query compilation is significantly improved and often obviates the need for explicit compiled queries using `EF.CompileQuery`. EF Core's internal caching mechanism is now much more efficient at recognizing and reusing query plans for similar queries. However, in some niche scenarios or very high-throughput systems, manually compiled queries might still offer a marginal performance benefit. Always benchmark your specific use case to determine if `EF.CompileQuery` is actually providing a measurable improvement.