Sub topic 4
The DbContext and DbSet Properties
In the last chapter you wrote entity classes: plain C# classes such as Blog and Post. Those classes are not connected to a database yet. In this chapter you add the piece that makes the connection, the DbContext. You will also learn what a DbSet is and how EF Core uses both to build its picture of your data.
What a DbContext is
A DbContext is a class from EF Core that stands between your code and the database. You never use the DbContext class directly. Instead, you write your own class that inherits from it. A class that inherits from another class gets all of that class's features and can add its own.
Your context class has several jobs:
- It holds the model. The model is EF Core's description of your entities, their properties, and how they map to tables and columns.
- It opens and closes the connection, which is the link your program uses to talk to the database.
- It turns your LINQ queries into SQL and runs them.
- It keeps track of the objects you load, so it can tell which ones you changed.
- It saves all of those changes when you call
SaveChanges.
A context also acts as a unit of work: a group of changes you collect and then save together in one step.
What a DbSet is
A DbSet is a property on your context that stands for one table. A DbSet<Blog> represents the Blogs table, and a DbSet<Post> represents the Posts table.
You use a DbSet in two ways:
- As the starting point for a query, such as
db.Blogs.Where(...). - As the place to add or remove entities, such as
db.Blogs.Add(blog).
Writing the context class
Here is the context for the blogging example. It uses the Blog and Post entities from the previous chapter.
using Microsoft.EntityFrameworkCore;
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; } = "";
public List<Post> Posts { get; } = new();
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; } = "";
public string Content { get; set; } = "";
public int BlogId { get; set; }
public Blog Blog { get; set; } = null!;
}
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs => Set<Blog>();
public DbSet<Post> Posts => Set<Post>();
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlite("Data Source=blogging.db");
}Here is what each part does:
class BloggingContext : DbContextcreates your own context, which inherits from EF Core'sDbContext.DbSet<Blog> Blogs => Set<Blog>();is a read-only property. Each time you read it, it asks the base class for the set ofBlogentities.OnConfiguringis a method EF Core calls to learn which database to use. Here it chooses SQLite and a file namedblogging.db. The next chapter covers this method in detail.
Two ways to write a DbSet property
You will often see DbSet properties written in another style:
public DbSet<Blog> Blogs { get; set; }Both styles work. When EF Core creates your context, it finds properties like this one and fills them in for you. The => Set<Blog>() style used in this tutorial has one advantage: it never holds null. That keeps the C# compiler from warning you about nullable reference types. A nullable reference type warning is the compiler telling you that a value might be null when you use it.
| Style | Example | Notes |
|---|---|---|
| Expression-bodied | `DbSet<Blog> Blogs => Set<Blog>();` | No null warnings. Read-only. |
| Auto-property | `DbSet<Blog> Blogs { get; set; }` | Common in older samples. Can cause null warnings unless you add `= null!;`. |
How EF Core builds the model
The first time you use a context, EF Core builds the model. It starts with your DbSet properties and then follows the links between classes.
EF Core follows a few rules here:
- Every type used in a DbSet property becomes an entity type.
- Any class reachable through a navigation property also becomes an entity type. A navigation property is a property that points to another entity, such as
Blog.Posts. - By default, the table name is the DbSet property's name. That is why the tables are called
BlogsandPosts, notBlogandPost.
Worked example: look inside the model
You can see the model without creating a database. Put the following code at the top of Program.cs, above the class definitions from earlier.
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
foreach (var entityType in db.Model.GetEntityTypes())
{
Console.WriteLine($"{entityType.ClrType.Name} -> table {entityType.GetTableName()}");
}Run it with dotnet run. The output is:
Blog -> table Blogs
Post -> table Postsdb.Model gives you the model EF Core built. GetEntityTypes() lists every entity type in it. GetTableName() shows the table each type maps to. No database file is needed, because building the model only reads your classes.
The lifetime of a context
A context is meant to be short-lived. You create one, do a single piece of work, and then throw it away. The using keyword does this for you:
using var db = new BloggingContext();
// work with db here
// db is disposed automatically at the end of the scopeDisposing an object means telling it to release what it holds, such as an open database connection. A using declaration disposes the context when the code leaves the current block.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Forgetting `: DbContext` | `Set<T>()` and `OnConfiguring` do not exist, so the code will not compile | Inherit from `DbContext` |
| Expecting `db.Blogs` to hold data | Nothing is loaded until a query runs | Call `ToList()`, `First()`, or a similar method |
| Keeping one context forever | Memory grows and changes from old work are still tracked | Create a new context per unit of work |
| Not disposing the context | Connections may stay open longer than needed | Use `using var db = ...` |
Exercise
You delete the line public DbSet<Post> Posts => Set<Post>(); from BloggingContext and run the model-inspection program again. Is Post still an entity type, and what table name does it map to?
Show answer
Yes, Post is still an entity type, because EF Core reaches it through the Blog.Posts navigation property. Without a DbSet property to take the name from, EF Core names the table after the class, so the output becomes "Post -> table Post".
Exercise
Why does the line var blogs = db.Blogs; not send any SQL to the database?
Show answer
A DbSet only represents a table and acts as the starting point for a query. EF Core runs SQL only when the query is executed, for example by calling ToList(), First(), or looping over the results with foreach.
Exercise
A teammate creates one BloggingContext in a static field and uses it for every request in a web app. Give two problems this causes.
Show answer
First, a context is not thread-safe, so requests that run at the same time can corrupt its state or throw errors. Second, the context keeps tracking every entity it has ever loaded, so memory use grows and saving gets slower. The fix is to create a short-lived context for each unit of work.