Catalog My learning Blog
Full-Stack Developer Course: React, .NET and SQL Server · Phase 4 · Lesson 33 · 6 min read

EF Core Tutorial: DbContext and Change Tracker

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: Entities, Configuration and a Tracked Update
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Set up Entity Framework Core with SQL Server, map entities using conventions and the Fluent API, understand how the change tracker and SaveChanges implement a unit of work, and configure the connection safely with resilience and least privilege.

Concept Explanation

Entity Framework Core is Microsoft's object-relational mapper. You describe your data as C# classes, and EF Core translates LINQ queries into SQL, materializes result rows into objects, and turns modifications of those objects into INSERT, UPDATE, and DELETE statements. If you have used Prisma or TypeORM in the JavaScript world, the role is the same, but EF Core is deeply integrated with LINQ and the .NET type system. It does not remove the need to understand SQL. It saves you from writing repetitive mapping code, and you must still know what SQL it generates, which Day 36 practices.

The central class is the DbContext. Each DbSet property on it represents a table you can query. A DbContext is a unit of work: it tracks the entities it has loaded or attached, remembers their original values, and when you call SaveChangesAsync it compares current values to originals and sends the minimal set of changes inside a single transaction. This is why the context has a short, per-request lifetime and is registered as a scoped service, as Day 15 explained, and why it is not thread-safe. Long-lived contexts accumulate tracked objects, grow stale, and eventually misbehave.

Mapping works by convention first: a class becomes a table, a property named Id becomes the key, and string properties become nvarchar max unless configured. Conventions rarely suffice for production, so you configure the model with the Fluent API, ideally in one IEntityTypeConfiguration class per entity to keep the DbContext tidy. There you set maximum lengths, required properties, precision, indexes, relationships, delete behavior, and concurrency tokens. Configuration must match the SQL you designed on Day 31. Setting explicit maximum lengths matters for security and performance as well as correctness, since it bounds stored data and lets the database enforce what the API validates.

Configuration and connection details affect security. Read the connection string from configuration, keep the password in user secrets or a secret store, or better, use passwordless authentication with a managed identity in Azure, which Phase 9 covers. Turn on EnableRetryOnFailure so transient network errors are retried, and use EnableSensitiveDataLogging only in local debugging, because it writes parameter values, and therefore personal data, into logs. Finally, connect as a login with only the required permissions, such as reading and writing the application tables, rather than owning the database, so a compromised API cannot drop tables.

ConceptRoleKey point
DbContextUnit of work and gateway to tablesShort-lived, scoped, not thread-safe
DbSet of TQueryable tableLINQ becomes SQL
Change trackerRemembers loaded entities and originalsDetects modifications automatically
SaveChangesAsyncFlushes changes in one transactionOne call, minimal UPDATE statements
Fluent API configurationPrecise mapping, lengths, indexesOne configuration class per entity
Connection resilienceEnableRetryOnFailureHandles transient errors

Worked Example: Entities, Configuration and a Tracked Update

The code defines two entities, configures them, registers the context, and shows a query and an update where EF Core works out the SQL from tracked changes. The commented SQL is what it sends.

C#
public class Project
{
    public Guid Id { get; set; }
    public string Name { get; set; } = "";
    public Guid OwnerId { get; set; }
    public byte[] RowVer { get; set; } = [];
    public List<TaskItem> Tasks { get; set; } = [];
}

public class TaskItem
{
    public Guid Id { get; set; }
    public Guid ProjectId { get; set; }
    public Project Project { get; set; } = null!;
    public string Title { get; set; } = "";
    public TaskState Status { get; set; }
    public decimal? Estimate { get; set; }
    public DateTimeOffset CreatedAt { get; set; }
    public byte[] RowVer { get; set; } = [];
}

public enum TaskState : byte { Todo = 0, InProgress = 1, Review = 2, Done = 3 }

public class ProjectConfiguration : IEntityTypeConfiguration<Project>
{
    public void Configure(EntityTypeBuilder<Project> b)
    {
        b.ToTable("Projects");
        b.HasKey(p => p.Id);
        b.Property(p => p.Name).HasMaxLength(120).IsRequired();
        b.Property(p => p.RowVer).IsRowVersion();                   // concurrency token
        b.HasMany(p => p.Tasks).WithOne(t => t.Project).HasForeignKey(t => t.ProjectId)
         .OnDelete(DeleteBehavior.Cascade);
    }
}

public class TaskItemConfiguration : IEntityTypeConfiguration<TaskItem>
{
    public void Configure(EntityTypeBuilder<TaskItem> b)
    {
        b.ToTable("Tasks");
        b.Property(t => t.Title).HasMaxLength(200).IsRequired();
        b.Property(t => t.Estimate).HasPrecision(9, 2);
        b.Property(t => t.RowVer).IsRowVersion();
        b.HasIndex(t => new { t.ProjectId, t.Status });
    }
}

public class AppDb(DbContextOptions<AppDb> options) : DbContext(options)
{
    public DbSet<Project> Projects => Set<Project>();
    public DbSet<TaskItem> Tasks => Set<TaskItem>();

    protected override void OnModelCreating(ModelBuilder mb) =>
        mb.ApplyConfigurationsFromAssembly(typeof(AppDb).Assembly);
}

// Program.cs
builder.Services.AddDbContext<AppDb>(o => o.UseSqlServer(
    builder.Configuration.GetConnectionString("Default"),
    sql => sql.EnableRetryOnFailure(maxRetryCount: 3))
    .EnableSensitiveDataLogging(builder.Environment.IsDevelopment()));            // never outside development
SQL
// Query and tracked update: EF works out the SQL from what changed.
var task = await db.Tasks.FirstAsync(t => t.Id == taskId, ct);
task.Status = TaskState.Done;                 // change tracker notices this single property
await db.SaveChangesAsync(ct);
// UPDATE Tasks SET Status = @p0 WHERE Id = @p1 AND RowVer = @p2;   (only the changed column)

Note how the update sends only the changed column and includes the row version in the WHERE clause. That is the concurrency check from Day 26 done by the database layer, which Day 37 examines closely.

Code loads a task. The DbContext tracks it and notices the single changed property, then SaveChanges sends one UPDATE that also checks the row version.
Code loads a task. The DbContext tracks it and notices the single changed property, then SaveChanges sends one UPDATE that also checks the row version.

Real-World Examples

  • Entity Framework Core 1.0 shipped in June 2016 as a ground-up rewrite of the older Entity Framework 6 to be cross-platform and modular, and it has since become the default data access library for new .NET applications. Microsoft's own reference application, eShop, uses EF Core for its services, and the framework's design as a unit of work with a change tracker underlies typical ASP.NET Core data access.
  • Sensitive data logging is a documented EF Core feature that includes parameter values in log output and exception messages, and Microsoft's documentation warns that it can expose personal data and must not be left on in production. It is a small setting with a large privacy consequence, and a common finding in log reviews.
Key TakeawaysA DbContext is a short-lived unit of work whose change tracker turns object modifications into minimal SQL on SaveChanges. Configure the model explicitly with the Fluent API to match your schema, enable retry on transient failures, keep secrets out of the connection string, and never enable sensitive data logging outside local development.

Review Questions & Answers

It tracks every entity it loads, so a long-lived context accumulates state, memory, and stale data, and it is not thread-safe, so concurrent use corrupts its internal tracking and throws errors. A scoped, per-request lifetime gives each unit of work a fresh, isolated context that is disposed when the request ends.

It compares each tracked entity's current property values with the original values recorded at load time, determines which entities were added, modified, or deleted, and generates only the necessary INSERT, UPDATE, and DELETE statements, executed together in one transaction. If any statement fails, the whole batch is rolled back.

Without a configured length, string properties map to nvarchar max, which removes a natural limit and can hurt indexing and performance. Matching the database column to the validation rule gives defense in depth: even if a bug skips validation, the database rejects oversized values instead of storing unbounded data.

It writes actual parameter values, such as emails and identifiers, into log messages and exceptions, so personal or secret data can end up in logs that many people and systems can read. It is acceptable only on a local development machine while debugging a specific problem, and should never be enabled in shared or production environments.