Nano ASP.NET SaaS 模板
管理员凭据(所有租户):admin@email.com / Password123!
样本数据每小时重置一次

Entity Framework C# Optimization Techniques

瑞安·刘易斯
8 月 12, 2025

Entity Framework Core is an incredibly powerful ORM — but with great power comes great responsibility.
If you’re not careful, a single LINQ statement can balloon into a massive SQL query, making performance terrible. I recently had this problem when building a SaaS tool. The problem was that some queries loaded a lot of related data, which very quickly resulted in out of memory exceptions. The problem was not easy to track down at first because the exceptions only happened on an Azure environment; everything worked fine on locally.

In this post, we’ll talk about four important concepts to keep your queries fast, predictable, ,以及 memory-friendly:

  • Split Queries
  • AsNoTracking
  • Cartesian Explosion
  • Projection with Automapper

A Cartesian explosion happens when EF Core loads related collections in a single query using multiple JOINs.
例如:

var blogs = 等待 上下文.Blogs
    .包含(b => b.Posts)
    .包含(b => b.评论)
    .ToListAsync();

Under the hood, EF Core might generate something like:

SELECT b.*, p.*, c.*
来自 Blogs b
LEFT JOIN Posts p ON b.Id = p.BlogId
LEFT JOIN 评论 c ON b.Id = c.BlogId

If a blog has 10 posts and 10 comments, you get 100 rows in memory for 1 blog — multiplying data unnecessarily.
This wastes memory, increases network payload, and slows everything down.

EF Core 5+ introduced Split Queries 用于 Include().
Instead of doing one huge JOIN, EF Core can load data in multiple SQL queries:

var blogs = 等待 上下文.Blogs
    .包含(b => b.Posts)
    .包含(b => b.评论)
    .AsSplitQuery()
    .ToListAsync();

Now EF Core sends:

-- First query
SELECT * FROM Blogs;

-- Second query
SELECT * 来自 Posts WHERE BlogId IN (...);

-- Third query
SELECT * 来自 评论 WHERE BlogId IN (...);

Advantages:

  • Avoids Cartesian explosion
  • Reduces duplicate data
  • Smaller memory footprint

Disadvantages:

  • More round-trips to the database
  • Slightly higher latency if your DB is far away

Tip: You can enable split queries globally:

optionsBuilder.UseSqlServer(connectionString, o => o.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery));

By default, EF Core tracks every entity it loads, so it can detect changes and persist them later.
But if you’re just reading data and not updating it, tracking is pure overhead.

var 产品 = 等待 上下文.产品
    .AsNoTracking()
    .ToListAsync();

Benefits:

  • Faster queries
  • Lower memory usage
  • No unnecessary ChangeTracker work

You can combine AsNoTracking() with split queries for maximum read performance.

If you don’t need the full entity, project directly into a DTO — skipping entity materialization entirely. While writing select statements to pull the columns you need is very tedious, Automapper takes care of that work for you. In the Nano 模板, any repository method that returns mapped DTOs uses projection.

Instead of:

var blogs = 等待 上下文.Blogs
    .包含(b => b.Posts)
    .AsNoTracking()
    .ToListAsync();

var dtos = _mapper.Map<列表<BlogDto>>(blogs); // Mapping in memory

You can use AutoMapper’s ProjectTo:

var dtos = 等待 _mapper.ProjectTo<BlogDto>(上下文.Blogs
    .AsNoTracking()
    .AsSplitQuery())
    .ToListAsync();

Why ProjectTo is better:

  • Executes mapping at the database level — only needed columns are selected
  • No unnecessary entity tracking
  • Prevents Cartesian explosion when combined with split queries
  • Avoids multiple passes over the data (no “load then map”)

Example DTO mapping:

public 类 BlogDto
{
    public int Id { get; set; }
    public 字符串 Title { get; set; }
    public 列表<PostDto> Posts { get; set; }
}

public 类 PostDto
{
    public int Id { get; set; }
    public 字符串 Title { get; set; }
}

public 类 BlogProfile : 个人简介
{
    public BlogProfile()
    {
        CreateMap<博客, BlogDto>();
        CreateMap<帖子, PostDto>();
    }
}

I ran a simple benchmark with 10,000 Blogs, each having 5 Posts 和 5 Comments, using SQL Server on a local machine.

ApproachRows ReturnedSQL QueriesTime (ms)Memory (MB)
Single Query + Include~250,0001850 ms220 MB
Split Query + Include~20,0003510 ms85 MB
AsNoTracking + Split Query~20,0003430 ms65 MB
AutoMapper ProjectTo (Split Query)~20,0003320 ms42 MB

The difference is especially dramatic in memory usage — projecting with AutoMapper’s ProjectTo can cut memory by more than half compared to naive includes. This is a basic example. In real world scenarios, its common to have several include statements, which would push the number of rows and memory up exponentially.

EF Core’s defaults prioritize simplicity, but for large read-heavy workloads, you need to be intentional:

  • 使用 split queries to avoid Cartesian explosion
  • 使用 AsNoTracking for read-only queries
  • 使用 projection (preferably with ProjectTo) to reduce payloads and skip unnecessary entity tracking

When combined, these techniques can deliver massive performance wins — both in speed and memory usage.

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

需要一个 ASP.NET 模板来构建您的下一个 MVP 吗?
快来看看这个 Nano ASP.NET 多租户 SaaS 模板项目,为您节省数周甚至数月的开发时间。.
了解更多