Create Entities
Create Entities in Entity Framework Core¶
Here we will create domain classes for our demo application and will see the difference between domain classes and entity classes of Entity Framework Core.
在这里,我们将为我们的演示应用程序创建领域类,并将看到领域类与 Entity Framework Core 的实体类之间的区别。
After installing the NuGet package of EF Core 6/7, it’s time to create domain classes. We are building a school application so here we will create two classes Student and Grade for the school domain.
在安装了 EF Core 6/7 的 NuGet 包后,是时候创建领域类了。我们正在构建一个学校应用程序,因此在这里我们将为学校领域创建两个类 Student 和 Grade。
Right click on the project in solution explorer and click Add -> Class.. Create two classes Student and Grade, as below.
在解决方案资源管理器中右键单击项目,点击“添加”->“类..” 创建两个类Student和Grade,如下所示。
![[Pasted image 20250413205535.png]]
Domain Classes
Write the following code in each class respectively.
在每个类中分别写入以下代码。
public class Student
{
public int StudentId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int GradeId { get; set; }
public Grade Grade { get; set; }
}
public class Grade
{
public Grade()
{
Students = new List<Student\>();
}
public int GradeId { get; set; }
public string GradeName { get; set; }
public IList<Student\> Students { get; set; }
}
{ get; set; }语法糖式的写法- 代码中的主键外键后面会详细讲解
The above Student class includes students related properties such as StudentId, FirstName, and LastName. It also includes the GradeId and Grade property which reference to the GradeId property of the Grade class. This is because each student belongs to any one grade and a grade can contain multiple students.
上述 Student 类包含学生相关的属性,如 StudentId、FirstName 和 LastName。它还包含引用 Grade 类的 GradeId 和 Grade 属性,这意味着每个学生属于一个年级,而一个年级可以包含多个学生。
These are our two simple domain classes but they are not become entities of Entity Framework yet. The terms "entities" and "domain classes" are often used interchangeably, but they are slightly different concepts.
这两个是我们简单的领域类,但它们还没有成为 Entity Framework 的实体。"实体"和"领域类"这两个术语常常可以互换使用,但它们是稍有不同的概念。
Entities in the Entity Framework are mapped to the corresponding tables in the database. Entity Framework keeps track of these entities so that It can perform database CRUD (Create, Read, Update, Delete) operations automatically based on their object’s status.
Entity Framework 中的实体与数据库中的相应表映射。Entity Framework 会跟踪这些实体,以便根据它们对象的状态自动执行数据库的 CRUD(创建、读取、更新、删除)操作。
Domain classes include the core functionality and business rules of the application, ensuring that the business logic is properly implemented.
领域类包含应用程序的核心功能和业务规则,确保业务逻辑得到正确实施。
The Student and Grade classes are domain classes. To treat them as entities, we need to include them as DbSet<T> properties in the DbContext class of Entity Framework so that EF engine can track their status.
Student和Grade类是领域类。为了将它们视为实体,我们需要在Entity Framework的DbContext类中将它们作为DbSet<T>属性包含,以便EF引擎能够跟踪它们的状态。
Let's create a DbContext class and specify these domain classes as entities in the next chapter.
让我们在下一章创建一个DbContext类,并将这些领域类指定为实体。