Entity-Framework基础6Entity-Framework中的实体

什么是Entity Framework中的实体?

Entity Framework中的实体是映射到数据库表的类。这个类必须作为DbSet<TEntity>类型属性被包含在DbContext类中。EF API将每个实体映射到表,并将实体的每个属性映射到数据库中的列。

举个例子,以下StudentGradeschool application中的领域类。

public class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public DateTime? DateOfBirth { get; set; }
    public byte[]  Photo { get; set; }
    public decimal Height { get; set; }
    public float Weight { get; set; }
        
    public Grade Grade { get; set; }
}

public class Grade
{
    public int GradeId { get; set; }
    public string GradeName { get; set; }
    public string Section { get; set; }

    public ICollection<Student> Students { get; set; }
}   

当上述类作为DbSet<TEntity>属性包含在上下文类(从DbContext派生的类)中时,它们将成为实体,如下所示。

public class SchoolContext : DbContext
{
    public SchoolContext()
    {

    }

    public DbSet<Student> Students { get; set; }
    public DbSet<Grade> Grades { get; set; }
}

在上面的上下文类中,DbSet<TEntity>类型的StudentsGrades属性称为实体集。StudentsGrades是实体。EF API将在数据库中创建Students表和Grades表,如下所示。


实体可以包括两种类型的属性:标量属性和导航属性。

标量属性

基本类型属性称为标量属性。每个标量属性都映射到数据库表中存储实际数据的列。举个例子,StudentIDStudentNameDateOfBirthPhotoHeightWeightStudent实体类中的标量属性。

public class Student
{
    // scalar properties
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public DateTime? DateOfBirth { get; set; }
    public byte[]  Photo { get; set; }
    public decimal Height { get; set; }
    public float Weight { get; set; }
        
    //reference navigation properties
    public Grade Grade { get; set; }
}

EF API将在数据库表中为每个标量属性创建一个列,如下所示。

导航属性

导航属性表示与另一个实体的关系。

导航属性有两种类型:参考导航和集合导航

参考导航属性

如果实体包含另一实体类型的属性,则称为参考导航属性。它指向单个实体,并表示实体关系中一个实体多重性。

EF API会在表中为导航属性创建一个外键列,该列指向数据库中另一个表的主键。举个例子,Grade是以下Student实体类中的参考导航属性。

public class Student
{
    // scalar properties
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public DateTime? DateOfBirth { get; set; }
    public byte[]  Photo { get; set; }
    public decimal Height { get; set; }
    public float Weight { get; set; }
        
    //reference navigation property
    public Grade Grade { get; set; }
}

在数据库中,EF API将在Students表中创建外键Grade_GradeId,如下所示。

集合导航属性

如果实体包含实体类型的泛型集合的属性,则称为集合导航属性。它代表许多的多样性。

EF API不会为实体的相关表中的集合导航属性创建任何列,但它在泛型集合的实体表中创建了一列。举个例子,以下Grade实体包含泛型集合导航属性ICollection<Student>。这里,Student实体被指定为泛型类型,因此EF API将在数据库的Students表中创建一个Grade_GradeId列。


详细了解导航属性如何在定义实体关系中发挥重要作用。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理