Sub topic 4
The DbContext and DbSet Properties
In the last chapter you wrote two entity classes, Blog and Post. They are plain C# classes, and they don't know anything about databases yet. The class that connects them to a database is called a DbContext.
What a DbContext Is
A DbContext is a class from EF Core that represents one working session with your database. It does three jobs:
- It knows which entity classes belong to your model.
- It turns your LINQ queries into SQL and runs them.
- It keeps track of changes you make to objects, so it can save them later.
You don't use DbContext directly. You write your own class that inherits from it. A class inherits from another when it gets all of that class's features and can add its own.
What a DbSet Is
A DbSet is a property on your context that stands for one table. DbSet<Blog> stands for the Blogs table. You use it to read rows and to add or remove rows.
Each entity you want as a table gets one DbSet property.
Writing the Context Class
Add this class to your project, next to Blog and Post:
using Microsoft.EntityFrameworkCore;
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 line does:
| Line | Meaning |
|---|---|
| `: DbContext` | Your class inherits from EF Core's `DbContext`. |
| `DbSet<Blog> Blogs => Set<Blog>();` | A read-only property that returns the set of blogs. |
| `OnConfiguring` | Tells EF Core which database to use. The next chapter covers this. |
The => Set<Blog>() form asks the context for its built-in set of that type. With it, you never have to assign the property yourself, and the compiler won't warn that it might be null.
Seeing What the Context Knows
You can ask the context which entities it found. This code doesn't touch the database, so it runs even before the database exists. Put it in Program.cs:
using var db = new BloggingContext();
foreach (var entityType in db.Model.GetEntityTypes())
{
Console.WriteLine(entityType.DisplayName());
}Run it with dotnet run. The output is:
Blog
Postusing var makes sure the context is cleaned up when you are done with it. A context is meant to live for a short time: create it, do some work, then dispose it.
Exercise
You add a new entity class called Comment and want a Comments table that you can query directly. What line do you add to BloggingContext?
Show answer
public DbSet<Comment> Comments => Set<Comment>();
Exercise
Why should you create a new DbContext for a unit of work and dispose it afterward, instead of keeping one forever?
Show answer
A DbContext represents one short working session. It tracks every object it loads, so a long-lived context keeps growing and can hold stale data. Short-lived contexts stay small and current.