Entity Framework Code-First(12):Configure One-to-Many
Configure One-to-Many Relationship:
Here, we will learn how to configure One-to-Many relationship between two entities in code-first. Take an example of Student and Standard (grade) entities where one Standard can include many Students. So the relation between Student and Standard entities would be one-to-many.
Visit Entity Relationship section to understand how EF manages one-to-one, one-to-many, and many-to-many relationships between the entities.
Configure One-to-Many relationship using DataAnnotations:
Consider the following Student and Standard entity.
public class Student
{
public Student() { } public int StudentId { get; set; }
public string StudentName { get; set; } public virtual Standard Standard { get; set; }
} public class Standard
{
public Standard()
{
Students = new List<Student>();
}
public int StandardId { get; set; }
public string Description { get; set; } public virtual ICollection<Student> Students { get; set; }
}
In the above example, Student entity includes navigation property Standard and Standard entity includes collection property for Student. This is the default convention to form one-to-many relationship.
We do not need to configure for one-to-many relationships either using DataAnnotations or Fluent API, if entity classes follow this convention.
EF code-first would create one-to-many relationship by adding Standard_StandardId column in the student table as shown below.
Entity includes ForeignKey Id property:
It is recommended to include foreign key property in an entity class. For example, if Student entity includes StandardId property which automatically becomes foreignkey property because it follows the convention for foreignkey <Type Name>Id.
If foreignkey property name is not as per the convention, for example, Student entity uses different name of foreignkey for Standard entity than StandardId then we need to apply ForeignKey attribute on a property.
For example, the following Student entity includes StandardRefId property.
public class Student
{
public Student() { } public int StudentId { get; set; }
public string StudentName { get; set; } public int StdandardRefId { get; set; } [ForeignKey("StandardRefId")]
public virtual Standard Standard { get; set; }
} public class Standard
{
public Standard()
{
StudentsList = new List<Student>();
}
public int StandardId { get; set; }
public string Description { get; set; } public virtual ICollection<Student> Students { get; set; }
}
In the above example, ForeignKey attribute is applied on Standard navigation property to specify foreignkey property name for Standard property. So now, EF will create StandardRefId column as a FK as shown below.

Configure One-to-Many relationship using Fluent API:
Here, we will learn configure One-to-Many relationship between Student and Standard entities using Fluent API.
Let’s configure one-to-many for following Student and Standard entities.
public class Student
{
public Student(){ } public int StudentId { get; set; }
public string StudentName { get; set; } public int StandardId { get; set; } public virtual Standard Standard { get; set; }
} public class Standard
{
public Standard()
{
StudentsList = new List<Student>();
}
public int StandardId { get; set; }
public string Description { get; set; } public virtual ICollection<Student> Students { get; set; }
}
Now, you can configure one-to-many as shown below.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//one-to-many
modelBuilder.Entity<Student>()
.HasRequired<Standard>(s => s.Standard) // Student entity requires Standard
.WithMany(s => s.Students); // Standard entity includes many Students entities }
Suppose Student and Standard entity class doesn't follow Code-First conventions for foreign key. Student class will include a different foreign key name for Standard than StandardId.
public class Student
{
public Student(){ } public int StudentId { get; set; }
public string StudentName { get; set; } //StdId is not following code first conventions name
public int StdId { get; set; } public virtual Standard Standard { get; set; }
} public class Standard
{
public Standard()
{
StudentsList = new List<Student>();
}
public int StandardId { get; set; }
public string Description { get; set; } public virtual ICollection<Student> Students { get; set; }
}
So now, you can use Fluent API to configure a One-to-Many relationship using Student entity classes, as shown below.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//one-to-many
modelBuilder.Entity<Student>()
.HasRequired<Standard>(s => s.Standard)
.WithMany(s => s.Students)
.HasForeignKey(s => s.StdId); }
As you can see, modelBuilder.Entity<Student>().HasRequired<Standard>(s => s.Standard) specifies that Student entity requires NotNull Standard navigation property. .WithMany(s => s.Students).HasForeignKey(s => s.StdId) specifies that the other side of Student (means Standard entity ) can include many Students in Students collection property and foreign key is StdId.
Another possible way: We can also start with Standard entity.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//configure one-to-many
modelBuilder.Entity<Standard>()
.HasMany<Student>(s => s.Students) Standard has many Students
.WithRequired(s => s.Standard) Student require one Standard
.HasForeignKey(s => s.StdId);Student includes specified foreignkey property name for Standard
}
The code shown above will create the following database:
Notice that StdId is Not Null column. So you must assign Standard with Student entity every time you add or update Student.
Nullable foreign key for one-to-many relationship.
Use HasOptional method instead of HasRequired method to make foreign key column nullable.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//one-to-many
modelBuilder.Entity<Student>()
.HasOptional<Standard>(s => s.Standard)
.WithMany(s => s.Students)
.HasForeignKey(s => s.StdId); }
Learn how to configure many-to-many relationship in the next section.
Entity Framework Code-First(12):Configure One-to-Many的更多相关文章
- Entity Framework Tutorial Basics(12):Model First
Model First development with Entity Framework: In the Model First approach, you create Entities, rel ...
- Entity Framework Code first(转载)
一.Entity Framework Code first(代码优先)使用过程 1.1Entity Framework 代码优先简介 不得不提Entity Framework Code First这个 ...
- Entity Framework Code First (三)Data Annotations
Entity Framework Code First 利用一种被称为约定(Conventions)优于配置(Configuration)的编程模式允许你使用自己的 domain classes 来表 ...
- Entity Framework Code First (二)Custom Conventions
---------------------------------------------------------------------------------------------------- ...
- Entity Framework Code First (一)Conventions
Entity Framework 简言之就是一个ORM(Object-Relational Mapper)框架. Code First 使得你能够通过C#的类来描述一个模型,模型如何被发现/检测就是通 ...
- Entity Framework Tutorial Basics(11):Code First
Code First development with Entity Framework: Entity Framework supports three different development ...
- Entity Framework Code First (七)空间数据类型 Spatial Data Types
声明:本文针对 EF5+, Visual Studio 2012+ 空间数据类型(Spatial Data Types)是在 EF5 中引入的,空间数据类型表现有两种: Geography (地理学上 ...
- Entity Framework Code First (四)Fluent API - 配置属性/类型
上篇博文说过当我们定义的类不能遵循约定(Conventions)的时候,Code First 提供了两种方式来配置你的类:DataAnnotations 和 Fluent API, 本文将关注 Flu ...
- Entity Framework Code First (八)迁移 Migrations
创建初始模型和数据库 在开始使用迁移(Migrations)之前,我们需要一个 Project 和一个 Code First Model, 对于本文将使用典型的 Blog 和 Post 模型 创建一个 ...
- Entity Framework Code First (六)存储过程
声明:本文只针对 EF6+ 默认情况下,Code First 对实体进行插入.更新.删除操作是直接在表上进行的,从 EF6 开始你可以选择使用存储过程(Stored Procedures) 简单实体映 ...
随机推荐
- curl常用指令
curl 发送GET请求获取标准输出 curl -I 显示http请求头 curl -i 显示请求头及输出内容 curl xxx > xxx 将输出重定向到本地文件(本地文件无需已存在,一般不写 ...
- Windows 7 比Windows XP 难用的功能
Windows 7 的搜索功能做得实在难用,不仅慢,还经常搜不到文件(明明存在的文件却搜不到).相比Windows XP,这个功能差的太远了. Windows 7 的无线连网功能,即使设置为不要自动连 ...
- jquery详解图片平滑滚动
jquery详解图片平滑滚动 随便写了个DOM,没有美观性,见谅 原理: 1.定义两组ul列表放图,第一个ul放5张图,第二个ul为空 2.为什么要用两个ul?因为要用到jQuery的克隆方法clon ...
- Codeforces 180C Letter:dp
题目链接:http://codeforces.com/problemset/problem/180/C 题意: 给你一个字符串s,长度为n. 让你将这个字符串变成“前面一段都是大写字母,后面一段都是小 ...
- jQuery学习(3)
可以在select中设置size属性的属性值,从而让下拉列表中的选项都显示出来. <!DOCTYPE html> <html> <head> <title&g ...
- C++(八)— 死锁原因及解决方法
1.死锁原因 死锁问题被认为是线程/进程间切换消耗系统性能的一种极端情况.在死锁时,线程/进程间相互等待资源,而又不释放自身的资源,导致无穷无尽的等待,其结果是任务永远无法执行完成. 打个比方,假设有 ...
- VS2013修改resource之后产生designer1.cs
1. Unload project2. Edit the csproj file.3. Search for <LastGenOutput>test1.Designer.cs</La ...
- 修改Hosts文件,禁止访问指定网页
不知道Hosts文件什么鬼的朋友可以在网上搜索一下(大牛勿喷- -) 访问网址时,先查询本地的Hosts文件,那么如果我们将Hosts文件中的网址与IP的映射修改之后,将访问错误的IP. 如在文件尾追 ...
- SSH Secure Shell 的使用
一,安装Secure Shell ,之后会出现SSH Secure Shell client 和SSH Secure File Transfer client 两个快捷方式. 需要服务器的IP地址,用 ...
- pthread_detach()函数
创建一个线程默认的状态是joinable. 如果一个线程结束运行但没有被join,则它的状态类似于进程中的Zombie Process,即还有一部分资源没有被回收(退出状态码). 所以创建线程者应该调 ...