DbContext in Entity Framework Core
The DbContext class is an integral part of the Entity Framework. An instance of DbContext represents a session with the database which can be used to query and save instances of your entities to a database. DbContext is a combination of the Unit Of Work and Repository patterns.
DbContext 类是实体框架的重要组成部分。DbContext 的实例代表与数据库的一个会话,可以用于查询和保存实体的实例到数据库中。DbContext 是工作单元和仓储模式的结合。
DbContext in EF Core allows us to perform the following tasks:
- Manage database connection
- Configure model & relationship
- Querying database
- Saving data to the database
- Configure change tracking
- Caching
- Transaction management
在 EF Core 中,DbContext 允许我们执行以下任务:
- 管理数据库连接
- 配置模型和关系
- 查询数据库
- 将数据保存到数据库
- 配置变更跟踪
- 缓存
- 事务管理
To use DbContext in our application, we need to create a class that derives from DbContext.
要在我们的应用程序中使用 DbContext,我们需要创建一个从 DbContext 继承的类。
Let's create a context class that derives the DbContext class, as shown below.
我们来创建一个继承自 DbContext 类的上下文类,如下所示。
public class SchoolContext : DbContext
{
}
SchoolContext类 vsDbContext类
DbContext 是 EF Core 提供的基类,不需要手动实现,直接继承即可。SchoolContext 是自定义类,继承DbContext,需包含:
DbSet<T>属性(定义表)。- 数据库连接配置(
OnConfiguring)。- 模型配置(
OnModelCreating,可选)。
The above SchoolContext class derives the DbContext class. It can be called a context class. This is an empty context class that does nothing. First of all, let's define entities here.
上述的 SchoolContext 类继承自 DbContext 类,可以称为上下文类。这是一个空的上下文类,不执行任何操作。首先,我们在这里定义实体。
We created the Student and Grade domain classes in the Create Entities chapter. We can turn domain classes into entities by specifying them as DbSet<TEntity> type properties. This will allow Entity Framework to track their changes and perform CRUD operations accordingly.
我们在[[Create Entities_20250324083756|创建实体]]章节中创建了 Student 和 Grade 域类。我们可以通过将它们指定为 DbSet<TEntity> 类型的属性,将域类转换为实体。这将使实体框架能够跟踪它们的变化并相应地执行 CRUD 操作。
public class SchoolContext : DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Grade> Grades { get; set; }
}
The DbSet<TEntity> type allows EF Core to query and save instances of the specified entity to the database. LINQ queries against a DbSet<TEntity> will be translated into queries against the database. EF Core API will create the Student and Grade table in the underlying SQL Server database where each property of these classes will be a column in the corresponding table.
DbSet<TEntity> 类型允许 EF Core 查询和保存指定实体的实例到数据库。针对 DbSet<TEntity> 的 LINQ 查询将被转换为对数据库的查询。EF Core API 将在底层的 SQL Server 数据库中创建 Student 和 Grade 表,这些类的每个属性都将是相应表中的一列。
Configure Database Connection¶
We have specified entities as DbSet<TEntity> properties, but we haven't specified the database name and database server info yet. We can override DbContext's OnConfiguring() method to configure the database and other options to be used for this context. This method is called for each instance of the context that is created.
我们已经将实体指定为 DbSet<TEntity> 属性,但尚未指定数据库名称和数据库服务器信息。我们可以重写 DbContext 的 OnConfiguring() 方法来配置将用于此上下文的数据库和其他选项。这个方法会在每个创建的上下文实例中被调用。
Let's override the OnConfiguring() method in the context class, as shown below.
让我们在上下文类中重写 OnConfiguring() 方法,如下所示。
public class SchoolContext : DbContext
{
//entities
public DbSet<Student> Students { get; set; }
public DbSet<Grade> Grades { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
}
}
Above, base.OnConfiguring(optionsBuilder) calls the base implementation, which does nothing. We can remove it and specify a connection string for the database in the OnConfiguring(), as shown below.
上面的 base.OnConfiguring(optionsBuilder) 调用了基类的实现,而基类的实现没有任何操作。我们可以去掉它,并在 OnConfiguring() 中指定数据库的连接字符串,如下所示。
public class SchoolContext : DbContext
{
//entities
public DbSet<Student> Students { get; set; }
public DbSet<Grade> Grades { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=SchoolDb;Trusted_Connection=True;");
}
}
In the above code, the optionsBuilder.UseSqlServer() is an extension method used to configure EF to use SQL Server as the database provider by specifying a database connection string.
在上面的代码中,optionsBuilder.UseSqlServer() 是一个扩展方法,用于通过指定数据库连接字符串来配置 EF 使用 SQL Server 作为数据库提供程序。
The string Server=(localdb)\\mssqllocaldb; Database=SchoolDb; Trusted_Connection=True; is a connection string to a database which we will communicate with. EF API will create the specified database if it does not exist.
字符串 Server=(localdb)\\mssqllocaldb; Database=SchoolDb; Trusted_Connection=True; 是一个与我们将要通信的数据库的连接字符串。如果指定的数据库不存在,EF API 会自动创建该数据库。
You can specify a connection string in multiple ways. You will learn it later.
您可以通过多种方式指定连接字符串。您稍后将学习这些方式。
The DbContext class also allows you to override the OnModelCreating() and ConfigureConventions() methods to configure the database model and default conventions of EF Core. Visit how to configure a DbContext class for more info.
DbContext 类还允许您重写 OnModelCreating() 和 ConfigureConventions() 方法,以配置数据库模型和 EF Core 的默认约定。有关更多信息,请访问 如何配置 DbContext 类。
Check DbContext's methods and properties for more info.
查看 DbContext 的 方法 和 属性 以获取更多信息。
At this point, our project contains three files, Program.cs, Student.cs, Grade.cs, and SchoolDbContext.cs, as shown below.
此时,我们的项目包含三个文件:Program.cs、Student.cs、Grade.cs 和 SchoolDbContext.cs,如下所示。
Let's learn how to use the context class and entities to create the database on the fly and perform CRUD operations in the next chapter.
在下章中,让我们学习如何使用上下文类和实体动态创建数据库并执行 CRUD 操作。