Skip to content

Instantly share code, notes, and snippets.

@davepcallan
Created November 25, 2025 15:42
Show Gist options
  • Select an option

  • Save davepcallan/e7317e02f99ffbb3068f8e79c2a3bb1e to your computer and use it in GitHub Desktop.

Select an option

Save davepcallan/e7317e02f99ffbb3068f8e79c2a3bb1e to your computer and use it in GitHub Desktop.
Entity Framework Tracking v No-Tracking example BenchmarkDotNet benchmark
using System;
using System.Collections.Generic;
using System.Linq;
using BenchmarkDotNet.Attributes;
using Microsoft.EntityFrameworkCore;
namespace Benchmarks;
[MemoryDiagnoser]
public class QueryTrackingBehavior
{
[Params(10)]
public int NumBlogs { get; set; }
[Params(20)]
public int NumPostsPerBlog { get; set; }
[GlobalSetup]
public void Setup()
{
Console.WriteLine("Setting up database...");
using var context = new BloggingContext();
context.Database.EnsureCreated();
BloggingContext.SeedData(NumBlogs, NumPostsPerBlog);
Console.WriteLine("Setup complete.");
}
[Benchmark(Baseline = true)]
public List<Post> AsTracking()
{
using var context = new BloggingContext();
return context.Posts.AsTracking().Include(p => p.Blog).ToList();
}
[Benchmark]
public List<Post> AsNoTracking()
{
using var context = new BloggingContext();
return context.Posts.AsNoTracking().Include(p => p.Blog).ToList();
}
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseSqlServer(@"Server=localhost;Database=Blogging;Trusted_Connection=True;TrustServerCertificate=true");
public static void SeedData(int numBlogs, int numPostsPerBlog)
{
using var context = new BloggingContext();
context.AddRange(
Enumerable.Range(0, numBlogs)
.Select(_ => new Blog { Url = "Some URL", Posts = Enumerable.Range(0, numPostsPerBlog)
.Select(_ => new Post() { Title = "Some Title", Content = "Some Content"}).ToList() }));
context.SaveChanges();
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public int Rating { get; set; }
public List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment