原文链接:https://www.entityframeworktutorial.net/code-first/configure-one-to-many-relationship-in-code-first.aspx

EF 6 Code-First系列文章目录:

这里我们将学习如何在两个实体(领域类)之间配置一对多的关系。
我们使用Student和Grade两个实体配置一对多的关系,一个Grade中可以有很多的Students。

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

在上面两个实体实现一对多关系之后,数据库中就会生成下面两个表:

一对多的关系,可以通过下面的方式进行配置:

  1. 通过默认的约定
  2. 使用Fluent API进行配置
通过默认约定配置一对多的关系

在EF中有某些约定,只要实体遵循这些约定,EF就会为我们在数据库自动生成一对多的关系数据表。你不用进行任何其他的配置。
我们来看看一对多关系的所有的约定情况吧:

约定1:

我们想要在Student实体和Grade实体之间建立一对多的关系,并且很多学生关联到一个Grade。这就意味着,每一个Student实体指向一个Grade。这种情况可以通过在Student类中包含一个Grade类型的导航属性做到,例如:

public class Student
{
public int Id { get; set; }
public string Name { 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; }
}

在上面的例子中,Student类包含了一个Grade类型的导航属性,这样就会在Students和Grades表之间生成一对多关系,并且生成外键Grade_GradeId:

请注意:因为应用类型的属性是可空的,所以在Students表中创建的外键列Grade_GradeId是可空的。你可以使用Fluent API配置不为空的外键列。

约定2:

另外一个约定就是,在主体实体中包含一个集合类型的导航属性,例如:

public class Student
{
public int StudentId { get; set; }
public string StudentName { 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; }
}

在上面例子中Grade实体中包含一个集合类型ICollection的导航属性Students.所以这种也会在Students和Grades表之间生成一对多的关系。生成的数据库结构和约定1中一样。

约定3:

在两个实体中,都包含导航属性:

public class Student
{
public int Id { get; set; }
public string Name { 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> Student { get; set; }
}

在上面的代码中,Student实体包含一个Grade类型的导航属性,同样,Grade实体包含一个集合类型ICollection的属性.结果也是在两个表之间生成一对多的关系。生成的数据库结果和约定1,约定2中一样。

约定4:

在两个实体中,完整的定义关系,也会根据约定生成一对多的关系表:

public class Student
{
public int Id { get; set; }
public string Name { get; set; } public int GradeId { get; set; }
public Grade Grade { get; set; }
} public class Grade
{ public int GradeId { get; set; }
public string GradeName { get; set; } public ICollection<Student> Student { get; set; }
}

在上面的例子中,Student实体中,包含一个外键属性GradeId,还有一个Grade类型的导航属性。这样就会生成一对多的关系表。并且Student表中生成的外键GradeId是不可空的:

enter description here

如果GradeId是可空的int类型,那么就会生成可空的外键:

public class Student
{
public int Id { get; set; }
public string Name { get; set; } public int? GradeId { get; set; }
public Grade Grade { get; set; }
}

上面的代码将会生成一个可空的外键GradeId,?只是类型Nullable的简写。

使用Fluent API配置一对多的关系

通常情况下,在EF中你不用配置一对多的关系,因为默认的约定,已经帮我们配置好了。然而你可以使用Fluent API来配置一对多的关系,比默认生成的表更好维护一点。

看看下面的Student和Grade实体:

public class Student
{
public int Id { get; set; }
public string Name { get; set; } public int CurrentGradeId { get; set; }
public Grade CurrentGrade { 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; }
}

你可以使用Fluent API,重写上下文类中的OnModelCreating方法,来给上面的代码配置一对多的关系:

public class SchoolContext : DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Grade> Grades { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// configures one-to-many relationship
modelBuilder.Entity<Student>()
.HasRequired<Grade>(s => s.CurrentGrade)
.WithMany(g => g.Students)
.HasForeignKey<int>(s => s.CurrentGradeId);
}
}

我们来一步步理解上面的代码:

  • 首先从一个实体类开始配置,所以modelBuilder.Entity()就是从Student实体开始配置。
  • 然后,.HasRequired(s => s.CurrentGrade)指定Student实体,必须要有CurrentGrade属性,这就会在数据库中生成一个不为空的外键。
  • 现在,现在就是配置关系的另外一边,也就是Grade实体。
  • .WithMany(g => g.Students)指定Grade实体包含很多Student实体,这里可以通过ICollcetion类型的属性推断出来。
  • 然后,如果Student实体,不遵循外键的约定【ID property convention】,我们就可以通过HasForeignKey方法指定外键的名称。
  • HasForeignKey(s => s.CurrentGradeId),指定了Student实体中的外键属性。

还有另外一种方式配置一对多关系,就是从Grade实体开始配置,而不是Student实体。下面的代码,生成的数据库和上面的代码生成的是一样的:

modelBuilder.Entity<Grade>()
.HasMany<Student>(g => g.Students)
.WithRequired(s => s.CurrentGrade)
.HasForeignKey<int>(s => s.CurrentGradeId);

代码生成的数据库结构如下:

使用Fluent API配置不为空的外键列

在约定1中,我们看到生成的一对多关系中,外键是可空的,为了生成不为空的外键列,我们可以这样,使用HasRequired方法:

modelBuilder.Entity<Student>()
.HasRequired<Grade>(s => s.CurrentGrade)
.WithMany(g => g.Students);
使用Fluent API配置级联删除

级联删除意味着:当父行被删除之后,自动删除相关的子行。例如:如果Grade被删除了,那么所有在这个Grade中的Students应该同样被自动删除。下面的代码,使用WillCascadeOnDelete方法配置级联删除:

modelBuilder.Entity<Grade>()
.HasMany<Student>(g => g.Students)
.WithRequired(s => s.CurrentGrade)
.WillCascadeOnDelete();

好了,一对多的关系就介绍到这里,下面一节讲解多对多关系。

12.翻译系列:EF 6 中配置一对多的关系【EF 6 Code-First系列】的更多相关文章

  1. 11.翻译系列:在EF 6中配置一对零或者一对一的关系【EF 6 Code-First系列】

    原文链接:https://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-fi ...

  2. 8.翻译系列: EF 6中配置领域类(EF 6 Code-First 系列)

    原文地址:http://www.entityframeworktutorial.net/code-first/configure-classes-in-code-first.aspx EF 6 Cod ...

  3. 20.1翻译系列:EF 6中自动数据迁移技术【EF 6 Code-First系列】

    原文链接:https://www.entityframeworktutorial.net/code-first/automated-migration-in-code-first.aspx EF 6 ...

  4. 20.翻译系列:Code-First中的数据库迁移技术【EF 6 Code-First系列】

    原文链接:https://www.entityframeworktutorial.net/code-first/migration-in-code-first.aspx EF 6 Code-First ...

  5. 19.翻译系列:EF 6中定义自定义的约定【EF 6 Code-First约定】

    原文链接:https://www.entityframeworktutorial.net/entityframework6/custom-conventions-codefirst.aspx EF 6 ...

  6. 9.翻译系列:EF 6以及EF Core中的数据注解特性(EF 6 Code-First系列)

    原文地址:http://www.entityframeworktutorial.net/code-first/dataannotation-in-code-first.aspx EF 6 Code-F ...

  7. css3笔记系列-3.css中的各种选择器详解,不看后悔系列

    点击上方蓝色字体,关注我 最详细的css3选择器解析 ​ 选择器是什么? 比较官方的解释:在 CSS 中,选择器是一种模式,用于选择需要添加样式的元素. 最常见的 CSS 选择器是元素选择器.换句话说 ...

  8. CentOS7系列--5.3CentOS7中配置和管理Kubernetes

    CentOS7配置和管理Kubernetes Kubernetes(k8s)是自动化容器操作的开源平台,这些操作包括部署,调度和节点集群间扩展.如果你曾经用过Docker容器技术部署容器,那么可以将D ...

  9. CentOS7系列--5.2CentOS7中配置和管理Docker

    CentOS7配置和管理Docker Docker是操作系统级别的虚拟化工具,它能自动化布署在容器中的应用 1. 安装Docker 1.1. 安装Docker相关软件 [root@server1 ~] ...

随机推荐

  1. Nightmare HDU1072

    非常标准的BFS 第一次写错了很多 1.到达4时设置为墙就好了  避免了死循环 2.不用开d数组   在结构体里面就行了 3.结构体初始化函数的写法: Node(int x=0,int y=0,int ...

  2. 【Java】 剑指offer(48) 最长不含重复字符的子字符串

    本文参考自<剑指offer>一书,代码采用Java语言. 更多:<剑指Offer>Java实现合集   题目 请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字 ...

  3. C++对文本文件的读取和输出

    本文转载自xmh_free 自己浏览了上方的博客,主要整理了一下关于C++对文件的输入输出方法,如果想看C语言的输入输出方法,可浏览上述链接的博客 C++读写函数 在C++中,对文件的操作是通过str ...

  4. C语言中的地址传递(传指针,传递给形参的指针仍然是实参指针的一份拷贝)

    先看一个例子:这个程序为什么会崩溃? #include <stdio.h> #include <stdlib.h> int f(int *q) { ; q = (int*)ma ...

  5. cmake使用笔记

    目录 cmake使用笔记 基本使用方法 相较于makefile的优点 常用语法 cmake_minimum_required project PROJECT_SOURCE_DIR set includ ...

  6. Java线程池深入理解

    之前面试baba系时遇到一个相对简单的多线程编程题,即"3个线程循环输出ADC",自己答的并不是很好,深感内疚,决定更加仔细的学习<并发编程的艺术>一书,到达掌握的强度 ...

  7. Session丢失的解决方法

    1.修改配置文件 <sessionState mode="StateServer" stateConnectionString="tcpip=127.0.0.1:4 ...

  8. UVA.12230.Crossing Rivers(期望)

    题目链接 /* 到达一条河时,船在河中的位置是随机的,所以船到达岸边需要的时间在 0~2l/v 均匀分布,所以船到岸的期望为 (0+2l/v)/2 过河需要 l/v 的时间,所以过一条河总的期望为 ( ...

  9. ab,qps 并发连接数

    并发连接数 = pv / 统计时间 * 页面衍生连接次数 * http响应时间 * 因数 / 其他web服务器 数量 pv = 并发连接数 * 统计时间 * 其他web服务器 数量/ 页面衍生连接次数 ...

  10. [模板][P3377]杜教筛

    Description: 求 $ \sum_{i=1}^n \phi(i) ,\sum_{i=1}^n \mu(i)$ Hint: \(n<=10^{10}​\) Solution: 考虑积性函 ...