原文链接: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. BZOJ1293 [SCOI2009]生日礼物 离散化

    欢迎访问~原文出处——博客园-zhouzhendong 去博客园看该题解 题目传送门 - BZOJ1293 题意概括 彩珠有N个,分为K种.每一个彩珠有一个对应的坐标.坐标上可以没有彩珠,多个彩珠也可 ...

  2. [OpenCV-Python] OpenCV 中的图像处理 部分 IV (二)

    部分 IVOpenCV 中的图像处理 OpenCV-Python 中文教程(搬运)目录 16 图像平滑 目标 • 学习使用不同的低通滤波器对图像进行模糊 • 使用自定义的滤波器对图像进行卷积(2D 卷 ...

  3. (转)Java按指定行数读取文件

    package test import java.io.File; import java.io.FileReader; import java.io.IOException; import java ...

  4. HDU 2844 Coins 【多重背包】(模板)

    <题目连接> 题目大意: 一位同学想要买手表,他有n种硬币,每种硬币已知有num[i]个.已知手表的价钱最多m元,问她用这些钱能够凑出多少种价格来买手表. 解题分析: 很明显,这是一道多重 ...

  5. hdu 2005 求第几天(水题)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2005 转载于:https://blog.csdn.net/tigerisland45/article/ ...

  6. GIF录制

    韩梦飞沙  韩亚飞  313134555@qq.com  yue31313  han_meng_fei_sha ============= 快手电脑版_快手_gif快手电脑版 GIF动画录制工具|GI ...

  7. luogu P4178 Tree

    题目链接 luogu P4178 Tree 题解 点分治 代码 // luogu-judger-enable-o2 #include<cstdio> #include<algorit ...

  8. Python图形编程探索系列-07-程序登录界面设计

    设计任务 初步设计程序登录界面,详细分析设计步骤. 程序详细分析 基本框架设计 import tkinter as tk import tkinter.messagebox root = tk.Tk( ...

  9. [HDU5963]朋友

    [HDU5963]朋友 题目大意: 给定一棵\(n(n\le40000)\)个点的树,边权只能是\(0\)或\(1\).一局游戏开始时,会确定一个结点作为根.AB轮流操作.当一方操作时,他们需要先选择 ...

  10. Redis的使用(待更新)

    import redis #redis的使用 """ { "k1":"v1", 'names': ['把几个','鲁宁','把几个 ...