Queries and tracking
Queries and tracking
Tracking queries remember entity identity and changes within the context. No-tracking queries materialize results without registering those entities for later updates. Choose based on whether the operation reads data or edits it.
A tracking query may return the same object for the same key even after the database has changed; EF does not overwrite that object with fresh values by default. Find checks tracked entities before querying the database. AsNoTracking avoids normal tracking overhead and is useful for independent reads, but it is not invariably faster. AsNoTrackingWithIdentityResolution uses a temporary tracker to reuse entity instances within one result, without attaching them to the context. A projection containing entity objects may still track those objects; a projection of scalar fields alone does not. Use Select for read DTOs. Materialize with ToList or Single and choose explicit ordering before pagination. Count and Any are terminal operations and may translate to SQL. Tracking is not authorization; validate inputs and constrain queries to authorized rows. Save only intentional changes, not wholesale submitted entities.
Baseline: .NET 10 / C# 14, Microsoft.EntityFrameworkCore.Sqlite 10.0.15 (published package, restore and advisory checks pending). Each independent project includes its own complete source and project file. In an approved environment with a reviewed SDK and packages, restore from approved sources, then run dotnet build --no-restore and dotnet run --no-build in the fixture directory. Except for the migration-operation inspection, each uses its own open SQLite in-memory connection, synthetic catalog and schema created by EnsureCreated. No external database, account or credential is required. Expected results are reasoned, not executed.
Find the same tracked instance
Load the same key twice using Find and a query.
using Microsoft.Data.Sqlite;using Microsoft.EntityFrameworkCore;using var connection = new SqliteConnection("Data Source=:memory:;Foreign Keys=True");connection.Open();var options = new DbContextOptionsBuilder<Catalog>().UseSqlite(connection).Options;using var db = new Catalog(options);db.Database.EnsureCreated();db.Categories.Add(new Category { Id = 1, Name = "Science" });db.Books.AddRange(new Book { Id = 1, Title = "Atlas", Stock = 4, CategoryId = 1 }, new Book { Id = 2, Title = "Comet", Stock = 0, CategoryId = 1 });db.SaveChanges();db.ChangeTracker.Clear();var first = db.Books.Find(1)!;var second = db.Books.Single(b => b.Id == 1);Console.WriteLine(ReferenceEquals(first, second));Console.WriteLine(db.ChangeTracker.Entries<Book>().Count());class Book { public int Id { get; set; } public string Title { get; set; } = ""; public int Stock { get; set; } public int Revision { get; set; } = 1; public int CategoryId { get; set; } public Category? Category { get; set; }}class Category { public int Id { get; set; } public string Name { get; set; } = ""; public List<Book> Books { get; } = new();}class Catalog(DbContextOptions<Catalog> options) : DbContext(options) { public DbSet<Book> Books => Set<Book>(); public DbSet<Category> Categories => Set<Category>(); protected override void OnModelCreating(ModelBuilder model) { model.Entity<Book>().HasKey(b => b.Id); model.Entity<Book>().Property(b => b.Title).IsRequired(); model.Entity<Book>().Property(b => b.Revision).IsConcurrencyToken(); model.Entity<Book>().HasIndex(b => b.Title).IsUnique(); model.Entity<Book>().HasOne(b => b.Category).WithMany(c => c.Books) .HasForeignKey(b => b.CategoryId).OnDelete(DeleteBehavior.Restrict); }}Expected output (not executed):
True1Identity resolution avoids two tracked objects with the same key.
Edit a detached read result
Read without tracking, edit the object, and call SaveChanges.
using Microsoft.Data.Sqlite;using Microsoft.EntityFrameworkCore;using var connection = new SqliteConnection("Data Source=:memory:;Foreign Keys=True");connection.Open();var options = new DbContextOptionsBuilder<Catalog>().UseSqlite(connection).Options;using var db = new Catalog(options);db.Database.EnsureCreated();db.Categories.Add(new Category { Id = 1, Name = "Science" });db.Books.AddRange(new Book { Id = 1, Title = "Atlas", Stock = 4, CategoryId = 1 }, new Book { Id = 2, Title = "Comet", Stock = 0, CategoryId = 1 });db.SaveChanges();db.ChangeTracker.Clear();var book = db.Books.AsNoTracking().Single(b => b.Id == 1);book.Stock = 99;Console.WriteLine(db.Entry(book).State);Console.WriteLine(db.SaveChanges());Console.WriteLine(db.Books.AsNoTracking().Single(b => b.Id == 1).Stock);class Book { public int Id { get; set; } public string Title { get; set; } = ""; public int Stock { get; set; } public int Revision { get; set; } = 1; public int CategoryId { get; set; } public Category? Category { get; set; }}class Category { public int Id { get; set; } public string Name { get; set; } = ""; public List<Book> Books { get; } = new();}class Catalog(DbContextOptions<Catalog> options) : DbContext(options) { public DbSet<Book> Books => Set<Book>(); public DbSet<Category> Categories => Set<Category>(); protected override void OnModelCreating(ModelBuilder model) { model.Entity<Book>().HasKey(b => b.Id); model.Entity<Book>().Property(b => b.Title).IsRequired(); model.Entity<Book>().Property(b => b.Revision).IsConcurrencyToken(); model.Entity<Book>().HasIndex(b => b.Title).IsUnique(); model.Entity<Book>().HasOne(b => b.Category).WithMany(c => c.Books) .HasForeignKey(b => b.CategoryId).OnDelete(DeleteBehavior.Restrict); }}Expected output (not executed):
Detached04An ordinary CLR property change is not persisted unless the context is tracking it for an update.
Project a deterministic read model
Select only fields used by a stock report.
using Microsoft.Data.Sqlite;using Microsoft.EntityFrameworkCore;using var connection = new SqliteConnection("Data Source=:memory:;Foreign Keys=True");connection.Open();var options = new DbContextOptionsBuilder<Catalog>().UseSqlite(connection).Options;using var db = new Catalog(options);db.Database.EnsureCreated();db.Categories.Add(new Category { Id = 1, Name = "Science" });db.Books.AddRange(new Book { Id = 1, Title = "Atlas", Stock = 4, CategoryId = 1 }, new Book { Id = 2, Title = "Comet", Stock = 0, CategoryId = 1 });db.SaveChanges();db.ChangeTracker.Clear();var rows = db.Books.OrderBy(b => b.Id).Select(b => new { b.Title, b.Stock }).ToList();foreach (var row in rows) Console.WriteLine($"{row.Title}:{row.Stock}");Console.WriteLine(db.ChangeTracker.Entries<Book>().Count());class Book { public int Id { get; set; } public string Title { get; set; } = ""; public int Stock { get; set; } public int Revision { get; set; } = 1; public int CategoryId { get; set; } public Category? Category { get; set; }}class Category { public int Id { get; set; } public string Name { get; set; } = ""; public List<Book> Books { get; } = new();}class Catalog(DbContextOptions<Catalog> options) : DbContext(options) { public DbSet<Book> Books => Set<Book>(); public DbSet<Category> Categories => Set<Category>(); protected override void OnModelCreating(ModelBuilder model) { model.Entity<Book>().HasKey(b => b.Id); model.Entity<Book>().Property(b => b.Title).IsRequired(); model.Entity<Book>().Property(b => b.Revision).IsConcurrencyToken(); model.Entity<Book>().HasIndex(b => b.Title).IsUnique(); model.Entity<Book>().HasOne(b => b.Category).WithMany(c => c.Books) .HasForeignKey(b => b.CategoryId).OnDelete(DeleteBehavior.Restrict); }}Expected output (not executed):
Atlas:4Comet:00Scalar projections contain no entity instances to track. Ordering is explicit.
Apply the concept
Build a read-only list of out-of-stock titles and a separate stock-update operation. Explain tracking choices and what happens if the read model is modified.
Use the manual practice and knowledge check to reason about the boundary. Do not apply these examples to a production database.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Queries and tracking — knowledge check
Apply the lesson concepts to the following scenarios.
Which method skips ordinary entity tracking?
What happens if a detached entity is edited without attaching it?
What can Find return without a SQL round trip?
Which projection avoids tracking entities?
Is no-tracking always faster?