Tutorials / Advanced C# and .NET / Entity Framework Core basics: DbContext, migrations and queries

Entity Framework Core basics: DbContext, migrations and queries

16 min read csharp
Course contents (16 lessons)
  1. The type system
  2. Records, structs and value equality
  3. Interfaces and abstract classes
  4. Generics and constraints
  5. Delegates, events and lambdas
  6. Querying and matching data
  7. LINQ in depth: deferred execution, grouping and joins
  8. IEnumerable versus IQueryable
  9. Pattern matching in modern C#
  10. Async and await: how Task really works
  11. Async patterns: cancellation, timeouts and async streams
  12. Application structure
  13. Dependency injection and service lifetimes
  14. Configuration, options and logging
  15. Data and web
  16. Entity Framework Core basics: DbContext, migrations and queries
  17. Building a minimal API with ASP.NET Core
  18. Unit testing with xunit
  19. Performance and the final project
  20. Performance basics: Span of T and fewer allocations
  21. Final project: a notes API with EF Core, DI and logging

What EF Core does for you

Entity Framework Core (EF Core) is an object-relational mapper. You describe tables as C# classes. You query with LINQ. It generates the SQL, runs it, and turns the rows into objects. It also tracks changes to those objects and writes only the differences back to the database when you call SaveChanges.

It does not remove the need to understand SQL. It saves typing for common work, and you still need to know what it sends to the database.

Setting up

We use SQLite so no server is needed. Create a console project and add the packages:

dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet tool install --global dotnet-ef

The three parts of a model are entity classes, a DbContext and the configuration that connects them. An entity is a plain class with an Id. The context has one DbSet<T> per table.

using Microsoft.EntityFrameworkCore;

string dbPath = Path.Combine(Path.GetTempPath(), "library-demo.db");
if (File.Exists(dbPath)) File.Delete(dbPath);

await using var db = new LibraryContext(dbPath);
await db.Database.EnsureCreatedAsync();    // for demos; real projects use migrations

// Insert
var orwell = new Author { Name = "George Orwell" };
var tolkien = new Author { Name = "J.R.R. Tolkien" };
db.Books.AddRange(
    new Book { Title = "1984", Year = 1949, Author = orwell },
    new Book { Title = "Animal Farm", Year = 1945, Author = orwell },
    new Book { Title = "The Hobbit", Year = 1937, Author = tolkien });
await db.SaveChangesAsync();

// Query with a filter and sort
var old = await db.Books
    .Where(b => b.Year < 1948)
    .OrderBy(b => b.Year)
    .ToListAsync();
Console.WriteLine(string.Join(", ", old.Select(b => b.Title)));

// Include loads related data
var withAuthors = await db.Books.Include(b => b.Author).AsNoTracking().ToListAsync();
foreach (var b in withAuthors) Console.WriteLine($"{b.Title} by {b.Author.Name}");

// Projection: fetch only what you need
var summary = await db.Authors
    .Select(a => new { a.Name, Books = a.Books.Count })
    .ToListAsync();
foreach (var s in summary) Console.WriteLine($"{s.Name}: {s.Books} book(s)");

// Update through change tracking
var hobbit = await db.Books.SingleAsync(b => b.Title == "The Hobbit");
hobbit.Year = 1938;                       // just change the object
await db.SaveChangesAsync();              // UPDATE is generated here

// Bulk update and delete without loading entities
await db.Books.Where(b => b.Year < 1940).ExecuteDeleteAsync();
Console.WriteLine($"Books left: {await db.Books.CountAsync()}");

class Author
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public List<Book> Books { get; set; } = new();
}

class Book
{
    public int Id { get; set; }
    public string Title { get; set; } = "";
    public int Year { get; set; }
    public int AuthorId { get; set; }
    public Author Author { get; set; } = null!;
}

class LibraryContext(string path) : DbContext
{
    public DbSet<Author> Authors => Set<Author>();
    public DbSet<Book> Books => Set<Book>();

    protected override void OnConfiguring(DbContextOptionsBuilder options) =>
        options.UseSqlite($"Data Source={path}");

    protected override void OnModelCreating(ModelBuilder model)
    {
        model.Entity<Book>().Property(b => b.Title).HasMaxLength(200).IsRequired();
    }
}

Walking through it

Author and Book have a one-to-many relationship. By convention, EF Core sees AuthorId and Author on Book and creates the foreign key. OnModelCreating is where you override conventions, such as the maximum length of a column.

Inserting is two steps. Add or AddRange marks the objects as new. SaveChangesAsync sends the SQL in one transaction. Notice that I never added the authors directly. EF Core finds them through the books and inserts them first.

The Where and OrderBy lines are IQueryable operations from the previous lessons. They become a WHERE and an ORDER BY in SQL. Nothing is fetched until ToListAsync. Turn on logging, or call ToQueryString() on a query, to see the SQL it produces.

By default, related objects are not loaded. Include tells EF Core to join them. Without it, b.Author would be null. The AsNoTracking call says "I only read this, do not track changes", which saves memory and time on read-only queries.

The projection with Select is the habit I recommend most. Instead of loading whole entities, you ask for the exact values the screen needs. The count of books becomes a SQL COUNT inside the query, not a loop in your code.

The update shows change tracking. We loaded hobbit, changed a property, and called SaveChangesAsync. EF Core compared the object with the snapshot it took on load and sent an UPDATE for just that column. ExecuteDeleteAsync and ExecuteUpdateAsync run a single SQL statement for many rows without loading anything.

Migrations

EnsureCreated is fine for demos, but it cannot update a database when your model changes. Migrations do. They are versioned C# files that describe schema changes.

dotnet ef migrations add InitialCreate
dotnet ef database update
# later, after changing a class:
dotnet ef migrations add AddBookIsbn
dotnet ef database update

Commit the generated migration files to source control. Read them before you apply them, especially when a change renames a column, since EF Core may interpret a rename as a drop and an add, which deletes data. In production, generate a SQL script with dotnet ef migrations script or apply migrations as a deliberate deployment step.

Common mistakes

  • The N+1 problem. Looping over books and touching b.Author on each one, causing a query per book. Use Include or a projection.
  • Loading entire tables and filtering in memory with AsEnumerable.
  • Sharing one DbContext across threads or requests. It is not thread-safe and should be scoped, which is the default registration with AddDbContext.
  • Forgetting SaveChanges. Nothing is written until you call it.
  • Editing an applied migration. Add a new one instead.

Try it yourself

  1. Add a Genre string to Book, create a migration and update the database.
  2. Find authors who have more than one book using a Where on a.Books.Count.
  3. Print the SQL for one of your queries with ToQueryString() and read it.
csharp
using Microsoft.EntityFrameworkCore;

string dbPath = Path.Combine(Path.GetTempPath(), "library-demo.db");
if (File.Exists(dbPath)) File.Delete(dbPath);

await using var db = new LibraryContext(dbPath);
await db.Database.EnsureCreatedAsync();    // for demos; real projects use migrations

// Insert
var orwell = new Author { Name = "George Orwell" };
var tolkien = new Author { Name = "J.R.R. Tolkien" };
db.Books.AddRange(
    new Book { Title = "1984", Year = 1949, Author = orwell },
    new Book { Title = "Animal Farm", Year = 1945, Author = orwell },
    new Book { Title = "The Hobbit", Year = 1937, Author = tolkien });
await db.SaveChangesAsync();

// Query with a filter and sort
var old = await db.Books
    .Where(b => b.Year < 1948)
    .OrderBy(b => b.Year)
    .ToListAsync();
Console.WriteLine(string.Join(", ", old.Select(b => b.Title)));

// Include loads related data
var withAuthors = await db.Books.Include(b => b.Author).AsNoTracking().ToListAsync();
foreach (var b in withAuthors) Console.WriteLine($"{b.Title} by {b.Author.Name}");

// Projection: fetch only what you need
var summary = await db.Authors
    .Select(a => new { a.Name, Books = a.Books.Count })
    .ToListAsync();
foreach (var s in summary) Console.WriteLine($"{s.Name}: {s.Books} book(s)");

// Update through change tracking
var hobbit = await db.Books.SingleAsync(b => b.Title == "The Hobbit");
hobbit.Year = 1938;                       // just change the object
await db.SaveChangesAsync();              // UPDATE is generated here

// Bulk update and delete without loading entities
await db.Books.Where(b => b.Year < 1940).ExecuteDeleteAsync();
Console.WriteLine($"Books left: {await db.Books.CountAsync()}");

class Author
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public List<Book> Books { get; set; } = new();
}

class Book
{
    public int Id { get; set; }
    public string Title { get; set; } = "";
    public int Year { get; set; }
    public int AuthorId { get; set; }
    public Author Author { get; set; } = null!;
}

class LibraryContext(string path) : DbContext
{
    public DbSet<Author> Authors => Set<Author>();
    public DbSet<Book> Books => Set<Book>();

    protected override void OnConfiguring(DbContextOptionsBuilder options) =>
        options.UseSqlite($"Data Source={path}");

    protected override void OnModelCreating(ModelBuilder model)
    {
        model.Entity<Book>().Property(b => b.Title).HasMaxLength(200).IsRequired();
    }
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account