The Analogy: The Bridge Between Two Countries
Objects and tables are two countries with genuinely different laws. In object country a customer contains its orders, identity is a memory address, and following a reference costs nothing. In table country nothing contains anything: rows sit in flat sets, identity is a primary key, and relationships exist only as matching values joined on demand. Neither model is wrong; they were designed for different problems.
Entity Framework Core is the bridge. You describe your objects, it works out the tables; you write a LINQ query, it writes the SQL; you change a property, it works out the UPDATE. Crossing the bridge is so smooth that the easiest mistake is forgetting there are two countries at all — writing code that looks like an innocent loop over a collection and turns out to be four hundred separate round trips to a server in another building.
The bridge has a customs office, and it is called the change tracker. When EF Core loads an entity it keeps a snapshot of what the row looked like. When you call SaveChanges, it compares each tracked object against its snapshot and generates only the statements needed to reconcile the difference. Almost everything surprising about EF Core — why an object you never saved got saved, why a read-only query allocated twice as much as it needed to, why two updates collided — is the change tracker doing exactly what it was designed to do.
So the skill this lesson teaches is not "how to call ToList". It is keeping one eye on the SQL. You want the productivity of writing db.Customers.Where(...) and the awareness of an engineer who can predict, before running it, how many queries that line becomes and which columns come back.
Syntax or Core Structure
A model is plain classes plus a DbContext that names them. Everything else — table names, column types, keys, foreign keys — comes from convention until you override it in OnModelCreating:
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
class Customer
{
public int Id { get; set; } // convention: Id is the key
public string Name { get; set; } = "";
public List<Order> Orders { get; set; } = new(); // one-to-many
}
class Order
{
public int Id { get; set; }
public string Sku { get; set; } = "";
public int Quantity { get; set; }
public int UnitPriceCents { get; set; } // money as integer minor units
public int CustomerId { get; set; } // convention: the foreign key
public Customer Customer { get; set; } = null!; // the inverse navigation
}
class ShopContext : DbContext
{
public ShopContext(DbContextOptions<ShopContext> options) : base(options) { }
public DbSet<Customer> Customers => Set<Customer>();
public DbSet<Order> Orders => Set<Order>();
protected override void OnModelCreating(ModelBuilder model)
{
model.Entity<Customer>().HasIndex(c => c.Name).IsUnique();
model.Entity<Order>().Property(o => o.Sku).HasMaxLength(20).IsRequired();
}
}
class Program
{
static void Main()
{
// A SQLite in-memory database lives exactly as long as its connection,
// so the connection is held open for the whole program.
using var connection = new SqliteConnection("Data Source=:memory:");
connection.Open();
DbContextOptions<ShopContext> options =
new DbContextOptionsBuilder<ShopContext>()
.UseSqlite(connection)
.Options;
using (var db = new ShopContext(options))
{
db.Database.EnsureCreated(); // demo only - real apps migrate
var acme = new Customer { Name = "Acme Tools" };
acme.Orders.Add(new Order { Sku = "BOLT-01", Quantity = 40, UnitPriceCents = 125 });
acme.Orders.Add(new Order { Sku = "NUT-02", Quantity = 10, UnitPriceCents = 80 });
var borealis = new Customer { Name = "Borealis" };
borealis.Orders.Add(new Order { Sku = "BOLT-01", Quantity = 5, UnitPriceCents = 125 });
// Adding the customers is enough: EF walks the graph and finds the orders.
db.Customers.AddRange(acme, borealis);
int written = db.SaveChanges();
Console.WriteLine("rows written: " + written);
Console.WriteLine("acme id: " + acme.Id); // filled in by SaveChanges
}
using (var db = new ShopContext(options))
{
// One query: the projection and the aggregate both run on the server.
var summary = db.Customers
.AsNoTracking()
.OrderBy(c => c.Name)
.Select(c => new
{
c.Name,
Lines = c.Orders.Count(),
Cents = c.Orders.Sum(o => o.Quantity * o.UnitPriceCents)
})
.ToList();
foreach (var row in summary)
Console.WriteLine(row.Name.PadRight(12) + row.Lines + " " +
(row.Cents / 100m).ToString("0.00"));
Order biggest = db.Orders
.Include(o => o.Customer)
.OrderByDescending(o => o.Quantity * o.UnitPriceCents)
.First();
Console.WriteLine("biggest: " + biggest.Sku + " for " + biggest.Customer.Name);
}
}
}
Output:
rows written: 5
acme id: 1
Acme Tools 2 58.00
Borealis 1 6.25
biggest: BOLT-01 for Acme Tools
SaveChanges returned 5 — two customers and three orders — because adding a customer added everything reachable from it. That graph walk is why you rarely add child rows explicitly: EF Core discovers untracked objects hanging off a tracked one and inserts them in dependency order, parents first, so the foreign keys are available. Immediately afterwards acme.Id is 1 rather than 0, because EF Core reads generated keys back out of the INSERT and writes them onto your objects, then fixes up every CustomerId on the orders to match.
The query block shows the two habits worth building. AsNoTracking() says "I am not going to modify these", which skips the snapshot and the identity map entirely — for a read-only endpoint that is free performance and one less way to accidentally save something. And the Select projects to exactly three values, so the SQL is a GROUP BY returning three small rows instead of every column of every customer plus every column of every order. Include is the opposite tool: it says "load the real entity and its related entity", which is what you want when you are about to change something.
Technical Depth: The Change Tracker, Loading and Translation
Entity states
Every tracked entity has a state, and SaveChanges turns states into statements:
| State | How it gets there | SaveChanges emits |
|---|---|---|
Added | Add, AddRange, or found on a tracked graph | INSERT |
Unchanged | Loaded by a tracking query, snapshot matches | nothing |
Modified | A property changed since the snapshot | UPDATE of changed columns only |
Deleted | Remove, RemoveRange | DELETE |
Detached | Never tracked, or AsNoTracking, or the context was disposed | nothing |
The consequence people trip over: after a tracking query, customer.Name = "New" followed by SaveChanges() writes an UPDATE even though you never called an update method. There is no "save this one thing" API — SaveChanges saves everything the context is tracking, in one transaction. That transaction is automatic: if the third statement fails, the first two roll back.
The DbContext is a unit of work, not a service
A DbContext is cheap to create, not thread-safe, and designed to be short-lived — one per request, one per operation. Register it with AddDbContext<ShopContext>(o => o.UseSqlite(cs)), which gives a scoped lifetime by default.
- Never make it a singleton. Its change tracker would accumulate every entity the application has ever loaded, memory would grow without bound, and concurrent requests would corrupt each other's tracking.
- Never run two queries on one context concurrently.
Task.WhenAll(db.A.ToListAsync(), db.B.ToListAsync())throws; a context handles one operation at a time. - For background services that outlive a request, create a scope per unit of work with
IDbContextFactory<T>orIServiceScopeFactory.
Loading related data
| Strategy | Call | Round trips |
|---|---|---|
| Eager | .Include(o => o.Customer).ThenInclude(c => c.Address) | One (or one per Include with split queries) |
| Split | .Include(...).AsSplitQuery() | One per included collection |
| Explicit | db.Entry(customer).Collection(c => c.Orders).Load() | One, when you ask |
| Lazy | Proxies package plus virtual navigations | One per navigation touched, invisibly |
| Projection | .Select(c => new { c.Name, Count = c.Orders.Count() }) | One, only the columns named |
Lazy loading is the most dangerous of these because the cost is hidden inside a property access. A loop over a hundred customers that touches c.Orders is a hundred and one queries, and the code that causes it looks exactly like ordinary object traversal.
IQueryable composes; something must execute it
db.Orders.Where(...).OrderBy(...) builds an expression tree and sends nothing. Execution happens at ToList, ToListAsync, First, Single, Count, Any, Sum, or a foreach. Until then you can keep adding clauses, which is how conditional filters are built cleanly:
IQueryable<Order> q = db.Orders.AsNoTracking();
if (sku is not null)
q = q.Where(o => o.Sku == sku);
if (minQuantity > 0)
q = q.Where(o => o.Quantity >= minQuantity);
List<Order> page = await q.OrderBy(o => o.Id).Skip(20).Take(20).ToListAsync();
The moment you call .ToList() too early, everything after it runs in your process on rows already dragged across the network. And since EF Core 3.0 there is no silent fallback: if part of your Where cannot be translated to SQL, the query throws at runtime rather than quietly filtering in memory. That is a feature — a loud failure beats a query that reads a million rows to return five.
The escape hatches
Not everything belongs in LINQ. EF Core gives you three ways down to SQL without abandoning the model:
db.Orders.FromSql($"SELECT * FROM Orders WHERE Sku = {sku}")— a full entity query from your own SQL. The interpolated holes become parameters, not concatenated text, so this is safe;FromSqlRawwith a hand-built string is not.db.Database.ExecuteSql(...)for statements that return no rows.ExecuteUpdateandExecuteDeletefor set-based writes:db.Orders.Where(o => o.Sku == "OLD").ExecuteDelete()issues oneDELETEinstead of loading every row to remove it. These bypass the change tracker completely, so entities already in memory keep their stale values.
Optimistic concurrency
Two users editing the same row is not solved by transactions; the second write simply wins and the first user's change vanishes. Add a concurrency token — RowVersion on SQL Server, xmin on PostgreSQL, or any column marked IsConcurrencyToken() — and EF Core adds it to the WHERE clause of every UPDATE. If zero rows match, the row changed underneath you and SaveChanges throws DbUpdateConcurrencyException, which you catch to reload, merge or tell the user.
Real World Example: The N+1 That Ate the Dashboard
A customer dashboard showed a revenue total per customer. It was fine with twelve customers in development and took nine seconds with four hundred in production. Nobody had written a slow query — they had written a fast query inside a loop. The fix is three lines, but the useful part is seeing the problem, so this version counts the commands EF Core actually sends. It reuses the Customer, Order and ShopContext types from above:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
sealed class Counter { public int Commands; }
class Program
{
static void Main()
{
using var connection = new SqliteConnection("Data Source=:memory:");
connection.Open();
var counter = new Counter();
DbContextOptions<ShopContext> options =
new DbContextOptionsBuilder<ShopContext>()
.UseSqlite(connection)
// Count every command EF Core really sends to the database.
.LogTo(_ => counter.Commands++, new[] { RelationalEventId.CommandExecuted })
.Options;
Seed(options);
Report("naive", counter, () => Naive(options));
Report("projected", counter, () => Projected(options));
counter.Commands = 0;
using (var db = new ShopContext(options))
{
// Set-based write: one UPDATE, no entities loaded, tracker bypassed.
int rows = db.Orders
.Where(o => o.Sku == "BOLT-01")
.ExecuteUpdate(u => u.SetProperty(o => o.UnitPriceCents,
o => o.UnitPriceCents + 5));
Console.WriteLine("repriced: " + rows + " rows in " + counter.Commands + " command");
}
Report("after", counter, () => Projected(options));
}
// One query for the list, then one more for every row in it: the N+1.
static List<string> Naive(DbContextOptions<ShopContext> options)
{
using var db = new ShopContext(options);
var lines = new List<string>();
foreach (Customer c in db.Customers.OrderBy(c => c.Name).ToList())
{
int cents = db.Orders
.Where(o => o.CustomerId == c.Id)
.Sum(o => o.Quantity * o.UnitPriceCents);
lines.Add(c.Name.PadRight(12) + Money(cents));
}
return lines;
}
// The same answer, computed by the server, in a single round trip.
static List<string> Projected(DbContextOptions<ShopContext> options)
{
using var db = new ShopContext(options);
var rows = db.Customers
.AsNoTracking()
.OrderBy(c => c.Name)
.Select(c => new
{
c.Name,
Cents = c.Orders.Sum(o => o.Quantity * o.UnitPriceCents)
})
.ToList();
return rows.Select(r => r.Name.PadRight(12) + Money(r.Cents)).ToList();
}
static void Report(string label, Counter counter, Func<List<string>> work)
{
counter.Commands = 0;
List<string> rows = work();
Console.WriteLine(label.PadRight(11) + counter.Commands + " command(s)");
foreach (string row in rows)
Console.WriteLine(" " + row);
}
static string Money(int cents) => (cents / 100m).ToString("0.00");
static void Seed(DbContextOptions<ShopContext> options)
{
using var db = new ShopContext(options);
db.Database.EnsureCreated();
db.Customers.AddRange(
new Customer
{
Name = "Acme Tools",
Orders =
{
new Order { Sku = "BOLT-01", Quantity = 40, UnitPriceCents = 125 },
new Order { Sku = "NUT-02", Quantity = 10, UnitPriceCents = 80 }
}
},
new Customer
{
Name = "Borealis",
Orders = { new Order { Sku = "BOLT-01", Quantity = 5, UnitPriceCents = 125 } }
},
new Customer
{
Name = "Cascade",
Orders =
{
new Order { Sku = "WASHER-03", Quantity = 100, UnitPriceCents = 15 },
new Order { Sku = "BOLT-01", Quantity = 12, UnitPriceCents = 125 }
}
});
db.SaveChanges();
}
}
Output:
naive 4 command(s)
Acme Tools 58.00
Borealis 6.25
Cascade 30.00
projected 1 command(s)
Acme Tools 58.00
Borealis 6.25
Cascade 30.00
repriced: 3 rows in 1 command
after 1 command(s)
Acme Tools 60.00
Borealis 6.50
Cascade 30.60
Both versions print identical numbers, which is exactly what makes this bug survive code review. 4 against 1 with three customers looks trivial; the shape is N + 1, so four hundred customers means four hundred and one round trips. Each one is a fraction of a millisecond of query time and a full network round trip of latency, which is why the dashboard was fast locally — where the database was on the same machine — and slow in production, where it was not.
The projected version is not faster because LINQ is clever. It is faster because the Sum inside the Select is translated into the SQL, so the server does the aggregation over rows it already has on disk and sends back three numbers. The naive version sends four statements and three integers, but pays four latencies to do it. When you are diagnosing this for real, LogTo with RelationalEventId.CommandExecuted — or an ITelemetry-style interceptor — is the fastest way to see the count, because the count is the thing that matters and it is invisible in the C#.
ExecuteUpdate is the other half of the lesson. The obvious way to raise a price is to load every matching order, assign to UnitPriceCents, and call SaveChanges — that is one SELECT plus one UPDATE per row, with every entity snapshotted on the way through. ExecuteUpdate compiles the whole thing into a single UPDATE ... SET UnitPriceCents = UnitPriceCents + 5 WHERE Sku = 'BOLT-01' and reports three rows changed. For a set-based change over thousands of rows the difference is not a percentage, it is an order of magnitude.
The price of that shortcut is stated plainly in the output: it took effect in the database without the change tracker knowing. Any Order entity already loaded in a live context still holds 125, and saving it would write the stale value back. That is why the final Projected call opens a fresh context — and why ExecuteUpdate belongs in a well-marked maintenance or bulk path, not sprinkled through code that also tracks entities.
Common Mistakes
- Querying inside a loop. Any
db.call in the body of aforeachover query results is an N+1 waiting to happen. Load what you need in one query withIncludeor a projection, or fetch the children for the whole page at once and group them in memory. - Registering
DbContextas a singleton. The change tracker never empties, memory climbs all day, and concurrent requests trip over each other's entities. Scoped is the default for a reason; background work should create its own scope. - Calling
ToList()before the filter.db.Orders.ToList().Where(o => o.Sku == sku)loads the entire table and filters in your process. The difference between that anddb.Orders.Where(...).ToList()is invisible in the C# and enormous at runtime. - Tracking entities you only intend to read. Every entity from a tracking query gets a snapshot copy, roughly doubling allocations.
AsNoTracking()on read-only paths is close to free performance, and it removes the chance of an accidentalUPDATE. - Using
EnsureCreatedin a real application. It creates the schema from the current model and then refuses to evolve it, so the first change to an entity leaves you with a database it cannot update and no migration history. Use it in tests and demos only. - Assuming
Updateis needed to save a change. On a tracked entity, assigning a property is enough. Callingdb.Update(entity)marks every property modified, which writes columns you never touched and can clobber a concurrent change to a different field. - Ignoring concurrency entirely. Without a concurrency token, two users editing the same record means the later
SaveChangessilently overwrites the earlier one. The first user sees their change disappear and files a bug you cannot reproduce. - Mixing
ExecuteUpdatewith tracked entities in the same context. The set-based statement lands in the database, the tracker keeps the old snapshot, and a laterSaveChangeswrites the stale value back over it.
Best Practices
- Default to projections: select the fields the caller needs instead of loading whole entities, so the SQL returns the smallest useful result.
- Add
AsNoTracking()to every query whose results you will not modify, and let tracking be the deliberate choice for write paths. - Keep one
DbContextper request or per unit of work, registered withAddDbContext, and useIDbContextFactory<T>where you need one outside a request scope. - Use
awaitversions throughout —ToListAsync,FirstOrDefaultAsync,SaveChangesAsync— and pass aCancellationToken. - Watch the generated SQL during development with
LogToplusEnableSensitiveDataLogging()in the Development environment only, and count round trips rather than guessing. - Reach for
ExecuteUpdateandExecuteDeletefor set-based maintenance work, in a context that is not also tracking the affected entities. - Give every editable table a concurrency token and handle
DbUpdateConcurrencyExceptionwith a deliberate policy: reload, merge, or report the conflict to the user. - Keep
FromSqlinterpolated rather than raw so values become parameters, and treat any hand-built SQL string as the review-worthy exception it is.
Practice Exercises
- Count your own queries. Take the
CounterandLogTosetup from the example and wire it into a small model of your own. Write the same read three ways —Include,Include().AsSplitQuery(), and a projection — and record the command count and the number of columns each one returns. - Watch the change tracker work. Load a customer with a tracking query, print
db.Entry(customer).State, change the name, print the state again, then printdb.ChangeTracker.DebugView.ShortViewbefore and afterSaveChanges. Repeat the whole thing withAsNoTracking()and explain why the second run saves nothing. - Make a lost update impossible. Add a concurrency token to
Orderand write a test that loads the same order into two contexts, changes the quantity in both, and saves both. Confirm the secondSaveChangesthrowsDbUpdateConcurrencyException, then handle it by reloading and reapplying the change. - Compare the two ways to bulk edit. Insert ten thousand orders, then apply a five percent price rise twice: once by loading every entity and calling
SaveChanges, once withExecuteUpdate. Time both withStopwatch, count the commands each issues, and note what happens if you runExecuteUpdateon a context that already has those orders loaded.