原文链接: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. 081 Region的预分区

    1.预分区的方式 共有四种方式 2.帮助信息 help 'create' 3.第一种方式 4.在页面上查看效果(端口号:60010) 5.第二种方式 )创建文件,并在文件中书写分区的值 )创建表 6. ...

  2. fbs创建windows下安装qtpy应用程序!

    cd 到python3.6目录下Python -m venv venv 创建虚拟环境call venv\scripts\activate.bat 激活虚拟环境将pip升级到最新版19.2pip ins ...

  3. Floyd-傻子也能看懂的弗洛伊德算法(转)

                暑假,小哼准备去一些城市旅游.有些城市之间有公路,有些城市之间则没有,如下图.为了节省经费以及方便计划旅程,小哼希望在出发之前知道任意两个城市之前的最短路程.          ...

  4. Shell学习之Shell特性(一)

    Shell学习之Shell特性 目录 命令和文件自动补齐功能 命令历史记忆功能 history.上下键.!number.!string.!$.!! 别名功能 alias.unalias cp.~use ...

  5. Angular 个人深究(三)【由Input&Output引起的】

    Angular 个人深究(三)[由Input&Output引起的] 注:最近项目在做别的事情,angular学习停滞了 1.Angular 中 @Input与@Output的使用 //test ...

  6. Python3 图片水平镜像实现

    # -*- coding: utf-8 -*- """ Created on Sun Feb 4 12:15:38 2018 @author: markli " ...

  7. python 列表返回重复数据的下标

    class Solution(object): def searchRange(self, nums, target): """ :type nums: List[int ...

  8. CRC类(处理ITU表)

    class Crc { // CRC-ITU查找表 private static UInt16[] crctab16 = new UInt16[] { 0x0000, 0x1189, 0x2312, ...

  9. python-线程的暂停, 恢复, 退出

    我们都知道python中可以是threading模块实现多线程, 但是模块并没有提供暂停, 恢复和停止线程的方法, 一旦线程对象调用start方法后, 只能等到对应的方法函数运行完毕. 也就是说一旦s ...

  10. Project_Lemon测评系统安装经验

    历经千辛万苦才在我自己的Linux上装好了Lemon 因为毕竟没有什么使用Linux的经验然后踩了不少坑,同时为了所以就有了这篇文章. 本教程大部分都基于Linux,若有需要Windows下的帮助请看 ...