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.
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.
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:
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):
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();
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,foreachandawaitexecute SQL;WhereandSelectonly 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.Postsper item issues one query each when lazy loading is on. UseIncludeor a projection. - Not thread safe. A
DbContextmust 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 afterAsEnumerable()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).