Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท .NET, Tools and Concepts

Entity Framework Core overview

Reference overview of Entity Framework Core: DbContext, DbSet, LINQ queries, change tracking, migrations and loading related data, with runnable stand-ins.

Entity Framework Core (EF Core) is the object-relational mapper for .NET. You describe tables as plain classes, query them with LINQ, change the objects, and call SaveChanges(); EF Core writes the SQL. It supports SQL Server, PostgreSQL, SQLite, MySQL, Cosmos DB and an in-memory provider for tests.

EF Core is a NuGet package (Microsoft.EntityFrameworkCore plus a provider), which this site's runner does not include, so the EF code below is read-only. Two runnable examples demonstrate the ideas it is built on: LINQ translated from expression trees, and change tracking.

C#
public class ShopContext : DbContext
{
    public DbSet<Product> Products => Set<Product>();
}

using var db = new ShopContext();
var cheap = await db.Products.Where(p => p.Price < 10).OrderBy(p => p.Name).ToListAsync();

Try it

A query on IQueryable<T> does not run C# code; it records an expression tree that a provider translates to SQL. This program inspects the tree that Where receives, which is what EF Core does before building a WHERE clause.

C# LINQ becomes an expression tree

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.

DbContext is a unit of work: it remembers which objects it loaded and compares them with their original values when you save. A tiny version of that idea:

C# A stand-in for change tracking

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 statements printed here are illustrative; real EF Core sends parameterized SQL and wraps the batch in a transaction.

Syntax

A realistic model and workflow (read-only):

C#
public class Blog
{
    public int Id { get; set; }
    public required string Title { get; set; }
    public List<Post> Posts { get; } = [];
}

public class Post
{
    public int Id { get; set; }
    public int BlogId { get; set; }          // foreign key by convention
    public required string Text { get; set; }
}

public class BlogContext(DbContextOptions<BlogContext> options) : DbContext(options)
{
    public DbSet<Blog> Blogs => Set<Blog>();
    public DbSet<Post> Posts => Set<Post>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>().HasIndex(b => b.Title).IsUnique();
    }
}

// Registration (ASP.NET Core)
builder.Services.AddDbContext<BlogContext>(o => o.UseSqlite("Data Source=blog.db"));

// Query, change, save
var blogs = await db.Blogs.Include(b => b.Posts).Where(b => b.Title.Contains("net")).ToListAsync();
blogs[0].Posts.Add(new Post { Text = "Hello" });
await db.SaveChangesAsync();
TEXT
dotnet tool install --global dotnet-ef
dotnet ef migrations add InitialCreate
dotnet ef database update
Member Description
DbContext A session with the database and unit of work. Short-lived: one per request or operation.
DbSet<T> A table (or view) you can query and add to.
Add, Remove, Update Mark entities for insert, delete or update.
SaveChanges / SaveChangesAsync Sends all tracked changes in one transaction. Returns the number of rows affected.
Include, ThenInclude Eagerly load related data with a join.
AsNoTracking() Skip change tracking for read-only queries (faster, less memory).
ExecuteUpdateAsync, ExecuteDeleteAsync Set-based changes in SQL without loading entities.

Errors: DbUpdateException (constraint violations), DbUpdateConcurrencyException (a row changed since you read it, when a concurrency token is configured), InvalidOperationException when a LINQ expression cannot be translated.

Usage notes

  • Queries run when enumerated. ToList, First, Count, foreach and await execute SQL; Where and Select only build the query (Deferred execution).
  • Project in the database. Select(b => new { b.Id, b.Title }) reads only the columns you need.
  • The N+1 trap. Looping over blogs and touching blog.Posts per item issues one query each when lazy loading is on. Use Include or a projection.
  • Not thread safe. A DbContext must not be shared between threads. Register it as scoped.
  • Untranslatable code (your own methods inside Where) throws at runtime. Use members the provider knows, or filter after AsEnumerable() knowing the rest runs in memory.
  • Migrations version the schema in code. Review the generated files and apply them in deployment, not on app startup in production.
  • Raw SQL is available with FromSql($"... {value}"), which parameterizes interpolated values. Never concatenate user input into SQL.
  • Dapper and ADO.NET are lighter alternatives when you want to write the SQL yourself (Data access overview).