Sub topic 3
How Change Tracking Works
Change tracking
Change tracking is how EF Core remembers the entities it has loaded. Each tracked entity has a state, such as Unchanged, Modified, Added, or Deleted. When you call SaveChangesAsync, EF Core checks those states and writes only the changes to the database.
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
var blog = await db.Blogs.FirstAsync();
Console.WriteLine(db.Entry(blog).State); // Unchanged
blog.Url = "https://example.com/changed";
db.ChangeTracker.DetectChanges();
Console.WriteLine(db.Entry(blog).State); // Modified
await db.SaveChangesAsync();
Console.WriteLine(db.Entry(blog).State); // UnchangedIf you only need to read data, add AsNoTracking() to the query. EF Core then skips the tracking work, and the query runs faster.
More tools you will use
Each row below names a tool and when to reach for it.
| Tool | What it does |
|---|---|
| Data annotations | Attributes such as `[Required]` and `[MaxLength(100)]` placed on properties to set rules. |
| Fluent API | Code in `OnModelCreating` for settings like unique indexes. |
| Dependency injection | `AddDbContext` in ASP.NET Core creates one context per web request and passes it to your code. |
| `FromSql` | Runs your own SQL. It turns `{values}` into parameters, which blocks SQL injection. |
| `ExecuteUpdateAsync`, `ExecuteDeleteAsync` | Change many rows in one command without loading them first (EF Core 7 and later). |
| `BeginTransactionAsync` | Groups several saves so they all succeed or all roll back. |
| `[ConcurrencyCheck]` | Detects when another user changed the same row first and throws `DbUpdateConcurrencyException`. |
| `LogTo`, `ToQueryString` | Show the SQL that EF Core runs. |
SQL injection is an attack where someone sneaks harmful SQL into your query through user input. Never build SQL by joining strings together.
Testing data access code
To test your code, point the context at a SQLite database that lives in memory, using the connection string Data Source=:memory:. Keep that connection open for the whole test. Each test then starts with a fresh, empty database.
Exercise
You load 500 blogs only to show them on a web page and never change them. What should you add to the query, and why?
Show answer
Add AsNoTracking(). EF Core then does not track the entities, so it uses less memory and runs faster. Tracking only helps when you plan to change the data and save it.
Exercise
You need to add " (archived)" to the title of 10,000 posts. Why is ExecuteUpdateAsync better than loading the posts and calling SaveChangesAsync?
Show answer
ExecuteUpdateAsync sends a single UPDATE command to the database. It does not load or track 10,000 entities in memory.