Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 52 ยท Data Access

Entity Framework Core Overview

Learn what Entity Framework Core does: DbContext, entities, LINQ queries, change tracking, SaveChanges, relationships and migrations, with runnable stand-ins.

In the previous lesson you wrote SQL, ran it through ADO.NET and mapped rows to objects yourself. That is flexible but repetitive: for every table you write an INSERT, an UPDATE, a DELETE and a handful of SELECT statements, and you keep them in sync with your classes. Entity Framework Core (EF Core) is Microsoft's object-relational mapper (ORM) that does this work for you. You describe your data as C# classes, you query with LINQ, and EF Core generates the SQL, runs it and turns the rows back into objects.

An ORM is a trade. You write far less code, but a lot happens behind the scenes: SQL is generated, objects are tracked, changes are detected. The goal of this lesson is to make those hidden steps visible: what a DbContext is, how queries and SaveChanges work, what change tracking means, how relationships are modeled and what migrations do. The live runner cannot load EF Core (it is a NuGet package, and there is no database server), so the real EF code is read-only, and the runnable examples are small C# stand-ins that behave like the real thing in the ways that matter. The Entity Framework Core lesson in the C# tutorial covers the language side in more depth.

Entities and the DbContext

An entity is a plain class that maps to a table. By convention a property called Id (or ProductId) is the primary key, and a property named CustomerId next to a Customer property is a foreign key.

C#
public class Customer
{
    public int Id { get; set; }
    public required string Name { get; set; }
    public List<Order> Orders { get; } = [];
}

public class Order
{
    public int Id { get; set; }
    public decimal Total { get; set; }

    public int CustomerId { get; set; }      // foreign key
    public Customer? Customer { get; set; }  // navigation to the "one" side
}

A DbContext is your session with the database. It exposes one DbSet<T> per entity (think "table"), builds the model, tracks entities and saves changes.

C#
public class ShopContext(DbContextOptions<ShopContext> options) : DbContext(options)
{
    public DbSet<Customer> Customers => Set<Customer>();
    public DbSet<Order> Orders => Set<Order>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>()
            .Property(c => c.Name)
            .HasMaxLength(100);

        modelBuilder.Entity<Order>()
            .Property(o => o.Total)
            .HasPrecision(12, 2);
    }
}

Conventions give you most of the model for free. Where they are not enough you add configuration with attributes ([MaxLength(100)]) or the fluent API shown above. Registration in Program.cs is one line, and the provider (SQL Server, PostgreSQL, SQLite, ...) is a NuGet package:

C#
builder.Services.AddDbContext<ShopContext>(options =>
    options.UseSqlite(builder.Configuration.GetConnectionString("Shop")));

AddDbContext registers the context with a scoped lifetime, which means one instance per HTTP request. That is deliberate and important, as the example at the end of this lesson shows.

Querying with LINQ

Queries are LINQ expressions on a DbSet. EF Core translates the expression tree into SQL and runs it when you materialize the result (with ToListAsync, FirstOrDefaultAsync, CountAsync, an await foreach and so on). Until then you are just building a query.

C#
var bigSpenders = await db.Customers
    .Where(c => c.Orders.Sum(o => o.Total) > 1000m)
    .OrderBy(c => c.Name)
    .Select(c => new { c.Name, Orders = c.Orders.Count })
    .ToListAsync(ct);

Notice the Select with an anonymous type: EF Core generates SQL that fetches only those columns. A projection is usually the cheapest way to read data. The same lazy, composable behavior you know from LINQ applies, except that the work happens in the database. Anything EF Core cannot translate to SQL (your own helper method inside a Where, for example) fails with an exception instead of silently running in memory.

flowchart LR
    A["LINQ query"] --> B["EF Core translates<br/>to SQL"]
    B --> C["Provider sends SQL<br/>to the database"]
    C --> D["Rows come back"]
    D --> E["Materialized objects<br/>(tracked by default)"]

A query is only a description until you await a materializing method such as ToListAsync.

Change tracking and SaveChanges

When EF Core returns entities from a normal query, it tracks them: it keeps a reference to each object and a snapshot of its original property values. Each tracked entry has a state:

State Meaning What SaveChanges does
Unchanged Loaded, not modified nothing
Added New, via Add INSERT
Modified A tracked property differs from the snapshot UPDATE of the changed columns
Deleted Marked with Remove DELETE

You do not call "update". You change a property, and SaveChanges finds the difference, generates only the needed SQL and runs all statements in one transaction, so either everything is saved or nothing is.

C#
var customer = await db.Customers.FindAsync(1);
customer!.Name = "Ada Lovelace";          // tracked: now Modified
db.Orders.Add(new Order { CustomerId = 1, Total = 25m }); // Added
await db.SaveChangesAsync(ct);             // UPDATE + INSERT in one transaction

Two more facts help you reason about tracking. First, a context holds an identity map: asking for the same row twice returns the same object instance, not two copies. Second, tracking costs memory and time proportional to the number of entities, which is why read-only queries often add AsNoTracking() (see EF Core in Practice).

The stand-in below is a miniature of this machinery for a single entity type. It stores snapshots, detects which properties changed, prints the SQL it would send and applies the changes to an in-memory "table". Run it and watch the states change.

C# A miniature change tracker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Look at the generated SQL: the UPDATE sets only price, because that is the only property that differs from the snapshot, and the second SaveChanges does nothing because nothing changed. Real EF Core does the same comparison, batches statements into as few round trips as it can, and also reads back database-generated values such as the new Id.

Relationships

A relationship connects entities through a foreign key. EF Core finds them by convention from your navigation properties:

  • One-to-many: a Customer has many Orders; the order holds CustomerId. By far the most common.
  • One-to-one: both sides hold a single reference and one side carries the foreign key.
  • Many-to-many: Student.Courses and Course.Students as collections; EF Core creates the join table for you (a skip navigation), or you model the join entity yourself when it carries extra data such as an enrollment date.

Navigations are not loaded automatically. A query for orders returns Customer == null unless you ask for the related data with Include, project it with Select, or load it explicitly. EF Core also performs fixup: once both sides of a relationship are tracked in the same context, it connects them, even if they were loaded by different queries. The next stand-in shows both behaviors, including the surprise that a collection contains only what has been loaded so far.

C# Navigations and relationship fixup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The warning embedded in the output matters in real code: never assume customer.Orders is complete because you once loaded some orders. Load what you need with Include or a projection, and be deliberate about it.

Migrations: evolving the schema

Your model changes over time: a new property, a new table. Migrations are generated C# files that describe each schema change, in order, so every environment can be brought to the same shape. You work with them through the dotnet ef tool:

Terminal
dotnet tool install --global dotnet-ef
dotnet ef migrations add AddCustomerEmail     # compares model with the last snapshot, writes a migration
dotnet ef database update                     # applies pending migrations to the database
dotnet ef migrations script --idempotent      # SQL script for production deployments

A migration has an Up method (apply) and a Down method (undo). Review generated migrations like any other code: renaming a property can be read as "drop a column, add a column" and lose data unless you adjust it. In production, many teams generate an idempotent SQL script and run it from the deployment pipeline instead of letting the app migrate itself at startup.

Lifetime in a web app

Because DbContext is scoped and not thread-safe, ASP.NET Core creates one per request, shares it between everything handling that request, and disposes it at the end. That gives you a natural unit of work: all changes made during the request can be saved together. The stand-in below shows the lifetime rule with a fake context registered the same way AddDbContext registers a real one.

C# One scoped context per request

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Within one request every service receives the same context instance, each request gets a new one, and the container disposes it when the request ends. Never register a DbContext as a singleton and never store one in a static field: it would be shared by concurrent requests, grow forever as it tracks more entities, and throw because it is not thread-safe. For the long-running case there is IDbContextFactory<T>, which creates short-lived contexts on demand.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You load a Product with EF Core, change its Price and call SaveChanges. What SQL does EF Core send?

    EF Core keeps a snapshot of the loaded values, detects that Price differs and generates an UPDATE for that property. You never have to call an explicit update method for a tracked entity.
  2. 2. What does a DbContext lifetime of 'scoped' mean in an ASP.NET Core app?

    AddDbContext registers a scoped service. ASP.NET Core creates a scope per request, so all services in that request share one context, which is disposed afterwards.
  3. 3. An order is loaded by a query without Include. What is order.Customer?

    EF Core does not load navigation properties automatically. Fixup fills them only when both entities are tracked in the same context.
  4. 4. What is a migration?

    A migration has Up and Down methods that describe how to change the schema. dotnet ef migrations add generates it from model changes and dotnet ef database update applies it.
  5. 5. Why is it a bug to register a DbContext as a singleton?

    DbContext is designed for short, single-threaded units of work. A shared instance would break under concurrent use and keep growing as it tracks more entities.

Summary

  • EF Core maps C# entity classes to tables; a DbContext with DbSet<T> properties is your session with the database.
  • LINQ queries are translated to SQL and run when you materialize them; projections fetch only the columns you need.
  • Tracked entities have states (Unchanged, Added, Modified, Deleted); SaveChanges finds differences and sends the needed SQL in one transaction.
  • The identity map returns the same instance for the same row; relationship fixup connects tracked entities, but navigations are not loaded unless you ask.
  • Relationships are one-to-many, one-to-one and many-to-many, configured by convention, attributes or the fluent API.
  • Migrations (dotnet ef migrations add, database update) evolve the schema in ordered steps.
  • AddDbContext is scoped: one context per request, never a singleton.

Next: EF Core in Practice