Entity Framework Core Intro
Almost every web app stores data. Entity Framework Core (EF Core) is .NET's object-relational mapper (ORM): you work with ordinary C# classes and LINQ, and EF Core translates that into SQL for SQLite, SQL Server, PostgreSQL, MySQL and others. EF Core 9 ships alongside ASP.NET Core 9.
In the next four lessons we build a small blog API with two tables, Blogs and Posts.
The three pieces
| Piece | What it is |
|---|---|
| Entity | A plain C# class whose instances become rows (Blog, Post) |
DbContext |
Your session with the database; exposes one DbSet<T> per table and tracks changes |
| Provider | A NuGet package that knows one database's SQL dialect, e.g. Microsoft.EntityFrameworkCore.Sqlite |
Installing EF Core
Add the provider package (it pulls in EF Core itself) and the design-time package used by the dotnet ef tool:
$ dotnet add package Microsoft.EntityFrameworkCore.Sqlite --version 9.0.10
$ dotnet add package Microsoft.EntityFrameworkCore.Design --version 9.0.10 Determining projects to restore...
Writing /tmp/tmpk3Lx9a.tmp
info : Adding PackageReference for package 'Microsoft.EntityFrameworkCore.Sqlite' into project '/home/dev/BlogApi/BlogApi.csproj'.
info : Restoring packages for /home/dev/BlogApi/BlogApi.csproj...
info : Package 'Microsoft.EntityFrameworkCore.Sqlite' is compatible with all the specified frameworks in project '/home/dev/BlogApi/BlogApi.csproj'.
info : PackageReference for package 'Microsoft.EntityFrameworkCore.Sqlite' version '9.0.10' added to file '/home/dev/BlogApi/BlogApi.csproj'.
log : Restored /home/dev/BlogApi/BlogApi.csproj (in 2.31 sec).
Determining projects to restore...
Writing /tmp/tmpQ8vMbd.tmp
info : Adding PackageReference for package 'Microsoft.EntityFrameworkCore.Design' into project '/home/dev/BlogApi/BlogApi.csproj'.
info : PackageReference for package 'Microsoft.EntityFrameworkCore.Design' version '9.0.10' added to file '/home/dev/BlogApi/BlogApi.csproj'.
log : Restored /home/dev/BlogApi/BlogApi.csproj (in 1.04 sec).
Note: Keep EF Core package versions on the same major version as your target framework —
9.0.xpackages for anet9.0project.
Entities and the DbContext
Entities are normal classes. By convention a property named Id (or <TypeName>Id) becomes the primary key, and an int key is generated by the database.
// Models/Blog.cs
public class Blog
{
public int Id { get; set; }
public required string Title { get; set; }
public List<Post> Posts { get; set; } = [];
}
// Models/Post.cs
public class Post
{
public int Id { get; set; }
public required string Title { get; set; }
public string Body { get; set; } = "";
public DateTime PublishedOn { get; set; }
public int BlogId { get; set; } // foreign key
public Blog Blog { get; set; } = null!; // navigation
}
// Data/AppDbContext.cs
public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
public DbSet<Blog> Blogs => Set<Blog>();
public DbSet<Post> Posts => Set<Post>();
}Register the context in Program.cs. AddDbContext registers it as a scoped service, so every HTTP request gets its own instance:
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlite(builder.Configuration.GetConnectionString("Blog")));{
"ConnectionStrings": {
"Blog": "Data Source=blog.db"
}
}Using the context in endpoints
Inject AppDbContext into a handler and use LINQ plus SaveChangesAsync:
app.MapGet("/blogs", async (AppDbContext db) =>
await db.Blogs.OrderBy(b => b.Title).Select(b => new { b.Id, b.Title }).ToListAsync());
app.MapPost("/blogs", async (BlogInput input, AppDbContext db) =>
{
var blog = new Blog { Title = input.Title };
db.Blogs.Add(blog); // tracked as Added
await db.SaveChangesAsync(); // INSERT runs; blog.Id is filled in
return Results.Created(quot;/blogs/{blog.Id}", new { blog.Id, blog.Title });
});
record BlogInput(string Title);$ curl -s -X POST localhost:5000/blogs -H "Content-Type: application/json" -d '{"title":"Kitchen Notes"}'
$ curl -s -X POST localhost:5000/blogs -H "Content-Type: application/json" -d '{"title":"Bike Repairs"}'
$ curl -s localhost:5000/blogs{"id":1,"title":"Kitchen Notes"}
{"id":2,"title":"Bike Repairs"}
[{"id":2,"title":"Bike Repairs"},{"id":1,"title":"Kitchen Notes"}]
What change tracking means
A DbContext remembers every entity it loaded or was given, together with a state: Added, Unchanged, Modified or Deleted. SaveChanges turns those states into INSERT, UPDATE and DELETE statements in one transaction. The program below imitates that idea with a tiny in-memory "context":
using System;
using System.Collections.Generic;
using System.Linq;
var db = new FakeContext();
var kitchen = new Blog { Title = "Kitchen Notes" };
var bikes = new Blog { Title = "Bike Repairs" };
db.Add(kitchen);
db.Add(bikes);
db.SaveChanges();
Console.WriteLine(quot;Ids after save: {kitchen.Id}, {bikes.Id}");
kitchen.Title = "Kitchen Notebook";
db.MarkModified(kitchen);
db.Remove(bikes);
db.SaveChanges();
Console.WriteLine(quot;Rows left: {string.Join(", ", db.Table.Select(b => quot;{b.Id}:{b.Title}"))}");
class Blog { public int Id; public string Title = ""; }
class FakeContext
{
public List<Blog> Table { get; } = new();
private readonly Dictionary<Blog, string> states = new();
private int nextId = 1;
public void Add(Blog b) => states[b] = "Added";
public void Remove(Blog b) => states[b] = "Deleted";
public void MarkModified(Blog b) => states[b] = "Modified";
public void SaveChanges()
{
foreach (var (blog, state) in states.Where(s => s.Value != "Unchanged").ToList())
{
switch (state)
{
case "Added":
blog.Id = nextId++;
Table.Add(blog);
Console.WriteLine(quot;INSERT INTO Blogs (Title) VALUES ('{blog.Title}') -> Id {blog.Id}");
break;
case "Modified":
Console.WriteLine(quot;UPDATE Blogs SET Title = '{blog.Title}' WHERE Id = {blog.Id}");
break;
case "Deleted":
Table.Remove(blog);
Console.WriteLine(quot;DELETE FROM Blogs WHERE Id = {blog.Id}");
break;
}
states[blog] = state == "Deleted" ? "Detached" : "Unchanged";
}
}
}INSERT INTO Blogs (Title) VALUES ('Kitchen Notes') -> Id 1
INSERT INTO Blogs (Title) VALUES ('Bike Repairs') -> Id 2
Ids after save: 1, 2
UPDATE Blogs SET Title = 'Kitchen Notebook' WHERE Id = 1
DELETE FROM Blogs WHERE Id = 2
Rows left: 1:Kitchen Notebook
The real EF Core detects modifications automatically by comparing current values with a snapshot taken when the entity was loaded — you do not need to call anything like MarkModified.
Tip: EF Core also has an in-memory provider and SQLite's
:memory:mode, which are handy for experiments and tests, but use the real database engine whenever behaviour must match production.
Test yourself
Which lifetime does AddDbContext give your DbContext by default?
- Singleton
- Transient
- Scoped (one per request)
- Static
When does EF Core actually send an INSERT for an entity passed to db.Blogs.Add(blog)?
- Immediately inside Add
- When
SaveChanges/SaveChangesAsyncis called - When the request ends
- Only after a migration
What does the provider package such as Microsoft.EntityFrameworkCore.Sqlite contribute?
- The database-specific SQL generation and connection handling
- The
dotnet efcommand-line tool - Razor view support
- JSON serialization