10.Configure One-to-Many(配置一对多关系)【Code-First系列】
现在,我们将学习怎么配置一对多的关系。
Visit Entity Relationship section to understand how EF manages one-to-one, one-to-many, and many-to-many relationships between the entities.
Note: You do not need to configure for one-to-many relationships either using DataAnnotations or Fluent API, if entity classes follow the conventions.
请注意;如果你是按照默认的约定来命名属性的话,不用手动配置一对多的关系,因为Code-First默认约定,会自动帮我们搞定。
一、使用数据注解特性来,配置一对多的关系
先来看看,使用默认的约定,Code-First自动帮我们配置一对多的关系的例子吧:
Standard班级表,Student学生表,一个班级有多个学生,一个学生只能属于一个班级
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EF6
{
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public virtual Standard Standard { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EF6
{
public class Standard
{
public int StandardID { get; set; }
public string Description { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EF6
{
public class DbContextClass:DbContext
{
public DbContextClass()
: base("name=ConnectionString")
{
}
public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; }
}
}
然后运行程序,就自动生成数据库,我们看下默认约定,自动生成的数据库是啥样的:

上面的一对多的关系是Code-First默认帮我们搞定的。
It is recommended to include foreign key property in Student entity class. So, include StandardId as per default convention or use ForeignKey attribute to give a different name of the foreign key property. For example, the following code includes StandardRefId property for the foreign key.
现在我们来自己配置:
上面看到的外键名称,是默认生成的,我们现在自己弄个外键名字:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EF6
{
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public int StandardRefID { get; set; }
[ForeignKey("StandardRefID")]
public virtual Standard Standard { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EF6
{
public class Standard
{
public int StandardID { get; set; }
public string Description { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
}

二、使用Fluent API来配置一对多的关系:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EF6
{
public class DbContextClass:DbContext
{
public DbContextClass()
: base("name=ConnectionString")
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DbContextClass>());
}
public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//配置一对多的关系
modelBuilder.Entity<Student>().HasRequired(s => s.Standard).WithMany(s => s.Students);
base.OnModelCreating(modelBuilder);
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EF6
{
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
// public int StandardRefID { get; set; }
//[ForeignKey("StandardRefID")]
public virtual Standard Standard { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EF6
{
public class Standard
{
public int StandardID { get; set; }
public string Description { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
}
可以看到生成的数据库是这样的:

看到没有,虽然生成了一对多的关系,但是外键的名字,还是默认的,我想自定义,接着我们修改一下代码:
改动一下Student实体的代码,取消注释:
public int StandardRefID { get; set; }
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EF6
{
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public int StandardRefID { get; set; }
//[ForeignKey("StandardRefID")]
public virtual Standard Standard { get; set; }
}
}
然后改动上下文的代码:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EF6
{
public class DbContextClass:DbContext
{
public DbContextClass()
: base("name=ConnectionString")
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DbContextClass>());
}
public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//配置一对多的关系
modelBuilder.Entity<Student>().HasRequired(s => s.Standard).WithMany(s => s.Students).HasForeignKey(s=>s.StandardRefID);
base.OnModelCreating(modelBuilder);
}
}
}
然后又得到想要的数据库了:

后面将学习多对多的关系》》》
附上系列目录:
- 什么是Code First
- 简单的Code First例子
- Code-First 约定
- DB Initialization(数据库初始化)
- Inheritance Strategy(继承策略)
- Configure Domain Classes(配置领域类)
- DataAnnotations(数据注解)
- Fluent API
- Configure One-to-One(配置一对一关系)
- Configure One-to-Many(配置一对多关系)
- Configure Many-to-Many(配置多对多关系)
- Move Configurations(数据迁移)
- DB Initialization Strategy(数据库初始化策略)
10.Configure One-to-Many(配置一对多关系)【Code-First系列】的更多相关文章
- Entity Framework对同一张表配置一对多关系
在实际的项目开发中,可能会遇到同一张表同时保存自身和上级(或下级)的信息(一般是通过设置一个上级主键[ParentId]的列与主键[Id]关系) 例如:城市库,有国家.省.市...,省的ParentI ...
- Mybaties配置一对多关系sql实例
<!-- resultMap中的type表示返回什么类型的对象 --> <resultMap id="BaseGoods" type="com.cn.h ...
- 11.Configure Many-to-Many(配置多对多关系)【Code-First系列】
现在学习EF Code-First多对多的配置. 这里我们举例:学生和班级实体,一个学生可以选修多个课程,多个学生也可以选修同一个课程. 一.使用数据注解特性,配置多对多的关系 using Syste ...
- 12.翻译系列:EF 6 中配置一对多的关系【EF 6 Code-First系列】
原文链接:https://www.entityframeworktutorial.net/code-first/configure-one-to-many-relationship-in-code-f ...
- Entity Framework管理实体关系(二):管理一对二关系
在上一篇文章中,简单的介绍了使用Fluent API如何管理一对一的实体关系,在这篇文章中,接着介绍Fluent API如何管理一对多的实体关系. 要在数据库中配置一对多关系,我们可以依赖EF约定,还 ...
- Hibernate中用注解配置一对多双向关联和多对一单向关联
Hibernate中用注解配置一对多双向关联和多对一单向关联 Hibernate提供了Hibernate Annotations扩展包,使用注解完成映射.在Hibernate3.3之前,需单独下载注解 ...
- Mybatis配置一对多的关联关系(五)
问题:是查询一个部门中的员工? 一.web项目构架 二.lib文件的jar 三.配置大小配置和该工具类 1大配置mybatis-config.xml <?xml version="1. ...
- Hibernate关联关系配置(一对多、一对一和多对多)
第一种关联关系:一对多(多对一) "一对多"是最普遍的映射关系,简单来讲就如消费者与订单的关系. 一对多:从消费者角的度来说一个消费者可以有多个订单,即为一对多. 多对一:从订单的 ...
- IBatis 配置一对多
-------说明-------- IBatis 版本2.0 配置一对多 namespace = testDao ------------------ /** *班级的resultMap *Class ...
随机推荐
- 【转】成为Java顶尖程序员 ,看这10本书就够了
“学习的最好途径就是看书“,这是我自己学习并且小有了一定的积累之后的第一体会.个人认为看书有两点好处: 1.能出版出来的书一定是经过反复的思考.雕琢和审核的,因此从专业性的角度来说,一本好书的价值远超 ...
- mongodb搭建和基本语法
下载安装包 https://fastdl.mongodb.org/win32/mongodb-win32-x86_64-2008plus-ssl-3.0.0-signed.msi?_ga=1.2206 ...
- 单元测试模拟框架:Nsubstitute
Nsubstitute是一个开源的框架,源码是C#实现的.你可以在这里获得它的源码:https://github.com/nsubstitute/NSubstitute NSubstitut ...
- 关于大型网站技术演进的思考(二十一)--网站静态化处理—web前端优化—下【终篇】(13)
本篇继续web前端优化的讨论,开始我先讲个我所知道的一个故事,有家大型的企业顺应时代发展的潮流开始投身于互联网行业了,它们为此专门设立了一个事业部,不过该企业把这个事业部里的人事成本,系统运维成本特别 ...
- SQL Server 变更数据捕获(CDC)
标签:SQL SERVER/MSSQL SERVER/数据库/DBA/字段/对象更改 概述 变更数据捕获用于捕获应用到 SQL Server 表中的插入.更新和删除活动,并以易于使用的关系格式提供这些 ...
- JSP模板继承功能实现
背景 最近刚入职新公司,浏览一下新公司项目,发现项目中大多数JSP页面都是独立的.完整的页面,因此许多页面都会有如下重复的代码: <%@ page language="java&quo ...
- Webstorm 10 for mac osx 注册机,序列号,kegen
小菜最近get到mac体验机会,早就耳闻mac非常适合做开发,于是迫不及待的安装各种开发工具,不知不觉,轮到前端开发神器webstorm了,看了一下官网的价格,心拔凉拔凉的. 果断搜索注册机,搜到的结 ...
- Step by step 活动目录中添加一个子域
原创地址:http://www.cnblogs.com/jfzhu/p/4006545.html 转载请注明出处 前面介绍过如何创建一个域,下面再介绍一下如何在该父域中添加一个子域. 活动目录中的森林 ...
- C语言 · 寻找数组中的最大值
问题描述 对于给定整数数组a[],寻找其中最大值,并返回下标. 输入格式 整数数组a[],数组元素个数小于1等于100.输出数据分作两行:第一行只有一个数,表示数组元素个数:第二行为数组的各个元素. ...
- Spark DAGSheduler生成Stage过程分析实验
RDD.Action触发SparkContext.run,这里举最简单的例子rdd.count() /** * Return the number of elements in the RDD. */ ...