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的更多相关文章

  1. Entity Framework Tutorial Basics(12):Model First

    Model First development with Entity Framework: In the Model First approach, you create Entities, rel ...

  2. Entity Framework Code first(转载)

    一.Entity Framework Code first(代码优先)使用过程 1.1Entity Framework 代码优先简介 不得不提Entity Framework Code First这个 ...

  3. Entity Framework Code First (三)Data Annotations

    Entity Framework Code First 利用一种被称为约定(Conventions)优于配置(Configuration)的编程模式允许你使用自己的 domain classes 来表 ...

  4. Entity Framework Code First (二)Custom Conventions

    ---------------------------------------------------------------------------------------------------- ...

  5. Entity Framework Code First (一)Conventions

    Entity Framework 简言之就是一个ORM(Object-Relational Mapper)框架. Code First 使得你能够通过C#的类来描述一个模型,模型如何被发现/检测就是通 ...

  6. Entity Framework Tutorial Basics(11):Code First

    Code First development with Entity Framework: Entity Framework supports three different development ...

  7. Entity Framework Code First (七)空间数据类型 Spatial Data Types

    声明:本文针对 EF5+, Visual Studio 2012+ 空间数据类型(Spatial Data Types)是在 EF5 中引入的,空间数据类型表现有两种: Geography (地理学上 ...

  8. Entity Framework Code First (四)Fluent API - 配置属性/类型

    上篇博文说过当我们定义的类不能遵循约定(Conventions)的时候,Code First 提供了两种方式来配置你的类:DataAnnotations 和 Fluent API, 本文将关注 Flu ...

  9. Entity Framework Code First (八)迁移 Migrations

    创建初始模型和数据库 在开始使用迁移(Migrations)之前,我们需要一个 Project 和一个 Code First Model, 对于本文将使用典型的 Blog 和 Post 模型 创建一个 ...

  10. Entity Framework Code First (六)存储过程

    声明:本文只针对 EF6+ 默认情况下,Code First 对实体进行插入.更新.删除操作是直接在表上进行的,从 EF6 开始你可以选择使用存储过程(Stored Procedures) 简单实体映 ...

随机推荐

  1. 【leetcode刷题笔记】Letter Combinations of a Phone Number

    Given a digit string, return all possible letter combinations that the number could represent. A map ...

  2. 为什么要用redux?component自身管理自己的state难道不更解耦吗?

    这是前几天百度2面的时候,面试官问我的一个问题.说实话当时有点紧张,其实也没去细想,本身react我就学了2个多星期,虽然看过redux这些源码,不过这个问题好像我从来没想过. 那其实react官网本 ...

  3. 剑指offer之 二叉搜索树的后续遍历序列

    题目描述: 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果.如果是则输出Yes,否则输出No.假设输入的数组的任意两个数字都互不相同. public class Solution { ...

  4. javascript笔记(一)

    使用function关键字来定义函数,分为两种形式: 声明式函数定义: function add(m,n) { alert(m+n); } 这种方式等同于构造一个Function类的实例的方式: va ...

  5. FFmpeg 基本用法

    FFmpeg FFmpeg 基本用法 本课要解决的问题 1.FFmpeg的转码流程是什么? 2.常见的视频格式包含哪些内容吗? 3.如何把这些内容从视频文件中抽取出来? 4.如何从一种格式转换为另一种 ...

  6. NOI 模拟赛 #2

    得分非常惨惨,半个小时写的纯暴力 70 分竟然拿了 rank 1... 如果 OYJason 和 wxjor 在可能会被爆踩吧 嘤 T1 欧拉子图 给一个无向图,如果一个边集的导出子图是一个欧拉回路, ...

  7. ACM学习历程—HDU1695 GCD(容斥原理 || 莫比乌斯)

    Description Given 5 integers: a, b, c, d, k, you're to find x in a...b, y in c...d that GCD(x, y) = ...

  8. bzoj 1711 Dining吃饭 —— 最大流

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=1711 食物一列,牛拆点,饮料一列. 代码如下: #include<cstdio> ...

  9. python中http的一些编码转换

    http的数据需要2种编码解码. 1. url中的特殊字符转换, 比如",', :,//等 python3中通过urllib.parse.quote(..)和urllib.parse.unq ...

  10. C++STL 库中set容器应用

    #include<iostream> #include<cstdio> #include<set> using namespace std; set<int& ...