现在,我们将学习怎么配置一对多的关系。

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);
       }

    }
}

然后又得到想要的数据库了:

后面将学习多对多的关系》》》

附上系列目录:

10.Configure One-to-Many(配置一对多关系)【Code-First系列】的更多相关文章

  1. Entity Framework对同一张表配置一对多关系

    在实际的项目开发中,可能会遇到同一张表同时保存自身和上级(或下级)的信息(一般是通过设置一个上级主键[ParentId]的列与主键[Id]关系) 例如:城市库,有国家.省.市...,省的ParentI ...

  2. Mybaties配置一对多关系sql实例

    <!-- resultMap中的type表示返回什么类型的对象 --> <resultMap id="BaseGoods" type="com.cn.h ...

  3. 11.Configure Many-to-Many(配置多对多关系)【Code-First系列】

    现在学习EF Code-First多对多的配置. 这里我们举例:学生和班级实体,一个学生可以选修多个课程,多个学生也可以选修同一个课程. 一.使用数据注解特性,配置多对多的关系 using Syste ...

  4. 12.翻译系列:EF 6 中配置一对多的关系【EF 6 Code-First系列】

    原文链接:https://www.entityframeworktutorial.net/code-first/configure-one-to-many-relationship-in-code-f ...

  5. Entity Framework管理实体关系(二):管理一对二关系

    在上一篇文章中,简单的介绍了使用Fluent API如何管理一对一的实体关系,在这篇文章中,接着介绍Fluent API如何管理一对多的实体关系. 要在数据库中配置一对多关系,我们可以依赖EF约定,还 ...

  6. Hibernate中用注解配置一对多双向关联和多对一单向关联

    Hibernate中用注解配置一对多双向关联和多对一单向关联 Hibernate提供了Hibernate Annotations扩展包,使用注解完成映射.在Hibernate3.3之前,需单独下载注解 ...

  7. Mybatis配置一对多的关联关系(五)

    问题:是查询一个部门中的员工? 一.web项目构架 二.lib文件的jar 三.配置大小配置和该工具类 1大配置mybatis-config.xml <?xml version="1. ...

  8. Hibernate关联关系配置(一对多、一对一和多对多)

    第一种关联关系:一对多(多对一) "一对多"是最普遍的映射关系,简单来讲就如消费者与订单的关系. 一对多:从消费者角的度来说一个消费者可以有多个订单,即为一对多. 多对一:从订单的 ...

  9. IBatis 配置一对多

    -------说明-------- IBatis 版本2.0 配置一对多 namespace = testDao ------------------ /** *班级的resultMap *Class ...

随机推荐

  1. HTML input小结

    一.Input表示Form表单中的一种输入对象,其又随Type类型的不同而分文本输入框,密码输入框,单选/复选框,提交/重置按钮等,下面一一介绍. 1.type=text 输入类型是text,这是我们 ...

  2. Amoeba -- 阿里巴巴工程师的开源项目之一陈思儒

    http://www.kuqin.com/opensource/20081023/24026.html 个人博客 http://dbanotes.net/web/page/44 阿里巴巴分布式服务框架 ...

  3. 《.NET之美》消息及勘误

    <.NET之美>消息及勘误 编辑最终还是采用了<.NET之美>作为书名,尽管我一直觉得这个名字有点文艺了,而更倾向于使用<.NET专题解析>这个名称. 目前已经可以 ...

  4. HTML5- Canvas入门(六)

    已经第六章了,也差不多接近尾声,如果你从第一章耐心follow到本章结束,那你便能掌握canvas的大部分知识点(当然如果要精通,还是得多靠练习,做一些小案例). 今天我们要学习的是canvas的变形 ...

  5. 【译】PHP的变量实现(给PHP开发者的PHP源码-第三部分)

    文章来自:http://www.aintnot.com/2016/02/12/phps-source-code-for-php-developers-part3-variables-ch 原文:htt ...

  6. 自己动手写游戏:Flappy Bird

    START:最近闲来无事,看了看一下<C#开发Flappy Bird游戏>的教程,自己也试着做了一下,实现了一个超级简单版(十分简陋)的Flappy Bird,使用的语言是C#,技术采用了 ...

  7. Nginx内置变量

    $args #请求中的参数值 $query_string #同 $args $arg_NAME #GET请求中NAME的值 $is_args #如果请求中有参数,值为"?",否则为 ...

  8. Spring学习记录(六)---使用外部属性文件

    在bean配置资源或系统部署,如数据库的连接时,需要这样: 要包含相关jar包:c3p0.jar 和mysql.connector.jar xml配置: <bean id="dataS ...

  9. ES6学习记录

    前言 由于要学习React Native ,所以得用到ES6,故为运用React Native做一个铺垫 学习记录 一.变量 1.let let 与 var 作用相同,用于定义变量,但是作用域不同.不 ...

  10. Leetcode-2 Add Two Numbers

    #2. Add Two Numbers You are given two linked lists representing two non-negative numbers. The digits ...