什么是Entity Framework中的实体
Entity Framework中的实体是映射到数据库表的类。这个类必须作为DbSet类型属性包含在DbContext类中。EF API将每个实体映射到一个表,将实体的每个属性映射到数据库中的一个列。
例如,下面的Student和Grade是学校应用程序中的域类。
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>的Students和Grades属性称为实体集。Student和Grade是实体。EF API将在数据库中创建学生和成绩表,如下所示。

一个实体可以包括两种类型的属性:标量属性和导航属性。
标量属性
基本类型属性称为标量属性。每个标量属性映射到数据库表中存储实际数据的列。例如,studententid, StudentName, DateOfBirth, Photo, Height, Weight是Student实体类中的标量属性。
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; }
}
EF API将在数据库表中为每个标量属性创建一个列,如下所示。

导航属性
导航属性表示与另一个实体的关系。
有两种类型的导航属性:引用导航和集合导航
引用导航属性
如果实体包含另一种实体类型的属性,则称为引用导航属性。它指向单个实体,并表示实体关系中一(1)的多重性。
EF API将在表中为导航属性创建一个ForeignKey列,该列指向数据库中另一个表的PrimaryKey。例如,Grade是下面Student实体类中的引用导航属性。
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; }
}
在数据库中,EF API将在Students表中按照默认约定创建一个ForeignKey(外键) Grade_GradeId,如下所示。

集合导航属性
如果实体包含实体类型的泛型集合的属性,则称为集合导航属性。它表示多个(*)的多重性。
EF API不会在实体的相关表中为集合导航属性创建任何列,但它会在通用集合的实体的表中创建列。例如,以下Grade实体包含通用集合导航属性ICollection<Student>。在这里,Student实体被指定为泛型类型,因此EF API将在数据库中的Students表中创建一个列Grade_GradeId。
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; } //一个年级中有多个学生
}

实体与实体之间的对应关系我们会在后面详细介绍。
参考
- https://www.entityframeworktutorial.net/
- https://msdn.microsoft.com/
EntityFramework中的实体是映射到数据库表的类,如Student和Grade。这些类包含标量属性(如StudentID,StudentName)和导航属性(如Grade引用)。DbSet属性在DbContext中定义实体集,EFAPI根据这些类在数据库中创建表并建立关系。导航属性用于表示与其他实体的关系,分为引用导航(一对一)和集合导航(一对多)。
701

被折叠的 条评论
为什么被折叠?



