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

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. ASP.NET Web API 2.1支持Binary JSON(Bson)

    ASP.NET Web API 2.1内建支持XML.Json.Bson.form-urlencoded的MiME type,今天重点介绍下Bson.BSON是由10gen开发的一个数据格式,目前主要 ...

  2. 思维导图FreeMind

    什么是MindMap? MindMap(被译成思维导图或心智图)是一种思维工具,由英国的记忆之父托尼-博赞发明. MindMap是一种新的思维模式,它将左脑的逻辑.顺序.条例.文字.数字,以及右脑的图 ...

  3. 安卓动态调试七种武器之长生剑 - Smali Instrumentation

    安卓动态调试七种武器之长生剑 - Smali Instrumentation 作者:蒸米@阿里聚安全 0x00 序 随着移动安全越来越火,各种调试工具也都层出不穷,但因为环境和需求的不同,并没有工具是 ...

  4. 【译】.NET中六个重要的概念:栈、堆、值类型、引用类型、装箱和拆箱

    为何要翻译 一来是为了感受国外优秀技术社区知名博主的高质量文章,二来是为了复习对.NET技术的基础拾遗达到温故知新的效果,最后也是为了锻炼一下自己的英文读写能力.因为是首次翻译英文文章(哎,原谅我这个 ...

  5. JWS.Mono如何进行“在线安装”

    这里话就不多说了,使用方法如下: wget http://jhonge.net/down4load/1413998270361/jwsmono_net.sh chmod a+x jwsmono_net ...

  6. CentOS 7 网络配置

    Virtual box 安装了CentOS 7最小模式后马上用ifconfig命令查看网络情况,发现该命令不存在. [root@centos1 ~]# ifconfig -bash: ifconfig ...

  7. [转]Linux tar 命令

    一.使用介绍 1.名词区分 打包:将一大堆文件或目录变成一个总的文件[tar命令] 压缩:将一个大的文件通过一些压缩算法变成一个小文件[gzip,bzip2等] Linux中很多压缩程序只能针对一个文 ...

  8. php相对于java、js几点不太一样的地方

    1.PHP 变量作用域 在 PHP 中,可以在脚本的任意位置对变量进行声明. 变量的作用域指的是变量能够被引用/使用的那部分脚本. PHP 有三种不同的变量作用域: local(局部) global( ...

  9. SQL Server 2014新功能PPT

        本篇文章是我在公司内部分享SQL Server 2014新功能的PPT,在本PPT中我详细描述了SQL Server除了BI方面的新功能,以及提供了大量的测试.希望对大家有帮助.     请点 ...

  10. Python第一天 - 函数

    ---恢复内容开始--- (一)定义一个函数 def 函数名(参数): 函数体 return 返回值 例: def mySum(x , y): return int(x)+int(y)print(my ...