http://msdn.microsoft.com/zh-cn/data/jj591620

Configuring a Required-to-Optional Relationship (One-to–Zero-or-One)

The following example configures a one-to-zero-or-one relationship. The OfficeAssignment has the InstructorID property that is a primary key and a foreign key, because the name of the property does not follow the convention the HasKey method is used to configure the primary key.

  1. // Configure the primary key for the OfficeAssignment
  2. modelBuilder.Entity<OfficeAssignment>()
  3. .HasKey(t => t.InstructorID);
  4.  
  5. // Map one-to-zero or one relationship
  6. modelBuilder.Entity<OfficeAssignment>()
  7. .HasRequired(t => t.Instructor)
  8. .WithOptional(t => t.OfficeAssignment);

Configuring a Relationship Where Both Ends Are Required (One-to-One)

In most cases the Entity Framework can infer which type is the dependent and which is the principal in a relationship. However, when both ends of the relationship are required or both sides are optional the Entity Framework cannot identify the dependent and principal. When both ends of the relationship are required, use WithRequiredPrincipal or WithRequiredDependent after the HasRequired method. When both ends of the relationship are optional, use WithOptionalPrincipal or WithOptionalDependent after the HasOptional method.

  1. // Configure the primary key for the OfficeAssignment
  2. modelBuilder.Entity<OfficeAssignment>()
  3. .HasKey(t => t.InstructorID);
  4.  
  5. modelBuilder.Entity<Instructor>()
  6. .HasRequired(t => t.OfficeAssignment)
  7. .WithRequiredPrincipal(t => t.Instructor);

Configuring a Many-to-Many Relationship

The following code configures a many-to-many relationship between the Course and Instructor types. In the following example, the default Code First conventions are used to create a join table. As a result the CourseInstructor table is created with Course_CourseID and Instructor_InstructorID columns.

  1. modelBuilder.Entity<Course>()
  2. .HasMany(t => t.Instructors)
  3. .WithMany(t => t.Courses)

If you want to specify the join table name and the names of the columns in the table you need to do additional configuration by using the Map method. The following code generates the CourseInstructor table with CourseID and InstructorID columns.

  1. modelBuilder.Entity<Course>()
  2. .HasMany(t => t.Instructors)
  3. .WithMany(t => t.Courses)
  4. .Map(m =>
  5. {
  6. m.ToTable("CourseInstructor");
  7. m.MapLeftKey("CourseID");
  8. m.MapRightKey("InstructorID");
  9. });

Configuring a Relationship with One Navigation Property

A one-directional (also called unidirectional) relationship is when a navigation property is defined on only one of the relationship ends and not on both. By convention, Code First always interprets a unidirectional relationship as one-to-many. For example, if you want a one-to-one relationship between Instructor and OfficeAssignment, where you have a navigation property on only the Instructor type, you need to use the fluent API to configure this relationship.

  1. // Configure the primary Key for the OfficeAssignment
  2. modelBuilder.Entity<OfficeAssignment>()
  3. .HasKey(t => t.InstructorID);
  4.  
  5. modelBuilder.Entity<Instructor>()
  6. .HasRequired(t => t.OfficeAssignment)
  7. .WithRequiredPrincipal();

Enabling Cascade Delete

You can configure cascade delete on a relationship by using the WillCascadeOnDelete method. If a foreign key on the dependent entity is not nullable, then Code First sets cascade delete on the relationship. If a foreign key on the dependent entity is nullable, Code First does not set cascade delete on the relationship, and when the principal is deleted the foreign key will be set to null.

You can remove these cascade delete conventions by using:

modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>()
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>()

The following code configures the relationship to be required and then disables cascade delete.

  1. modelBuilder.Entity<Course>()
  2. .HasRequired(t => t.Department)
  3. .WithMany(t => t.Courses)
  4. .HasForeignKey(d => d.DepartmentID)
  5. .WillCascadeOnDelete(false);

Configuring a Composite Foreign Key

If the primary key on the Department type consisted of DepartmentID and Name properties, you would configure the primary key for the Department and the foreign key on the Course types as follows:

  1. // Composite primary key
  2. modelBuilder.Entity<Department>()
  3. .HasKey(d => new { d.DepartmentID, d.Name });
  4.  
  5. // Composite foreign key
  6. modelBuilder.Entity<Course>()
  7. .HasRequired(c => c.Department)
  8. .WithMany(d => d.Courses)
  9. .HasForeignKey(d => new { d.DepartmentID, d.DepartmentName });

Renaming a Foreign Key That Is Not Defined in the Model

If you choose not to define a foreign key on the CLR type, but want to specify what name it should have in the database, do the following:

  1. modelBuilder.Entity<Course>()
  2. .HasRequired(c => c.Department)
  3. .WithMany(t => t.Courses)
  4. .Map(m => m.MapKey("ChangedDepartmentID"));

Configuring a Foreign Key Name That Does Not Follow the Code First Convention

If the foreign key property on the Course class was called SomeDepartmentID instead of DepartmentID, you would need to do the following to specify that you want SomeDepartmentID to be the foreign key:

  1. modelBuilder.Entity<Course>()
  2. .HasRequired(c => c.Department)
  3. .WithMany(d => d.Courses)
  4. .HasForeignKey(c => c.SomeDepartmentID);
  1.  
  1. using System.Data.Entity;
  2. using System.Data.Entity.ModelConfiguration.Conventions;
  3. // add a reference to System.ComponentModel.DataAnnotations DLL
  4. using System.ComponentModel.DataAnnotations;
  5. using System.Collections.Generic;
  6. using System;
  7.  
  8. public class SchoolEntities : DbContext
  9. {
  10. public DbSet<Course> Courses { get; set; }
  11. public DbSet<Department> Departments { get; set; }
  12. public DbSet<Instructor> Instructors { get; set; }
  13. public DbSet<OfficeAssignment> OfficeAssignments { get; set; }
  14.  
  15. protected override void OnModelCreating(DbModelBuilder modelBuilder)
  16. {
  17. // Configure Code First to ignore PluralizingTableName convention
  18. // If you keep this convention then the generated tables will have pluralized names.
  19. modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
  20. }
  21. }
  22.  
  23. public class Department
  24. {
  25. public Department()
  26. {
  27. this.Courses = new HashSet<Course>();
  28. }
  29. // Primary key
  30. public int DepartmentID { get; set; }
  31. public string Name { get; set; }
  32. public decimal Budget { get; set; }
  33. public System.DateTime StartDate { get; set; }
  34. public int? Administrator { get; set; }
  35.  
  36. // Navigation property
  37. public virtual ICollection<Course> Courses { get; private set; }
  38. }
  39.  
  40. public class Course
  41. {
  42. public Course()
  43. {
  44. this.Instructors = new HashSet<Instructor>();
  45. }
  46. // Primary key
  47. public int CourseID { get; set; }
  48.  
  49. public string Title { get; set; }
  50. public int Credits { get; set; }
  51.  
  52. // Foreign key
  53. public int DepartmentID { get; set; }
  54.  
  55. // Navigation properties
  56. public virtual Department Department { get; set; }
  57. public virtual ICollection<Instructor> Instructors { get; private set; }
  58. }
  59.  
  60. public partial class OnlineCourse : Course
  61. {
  62. public string URL { get; set; }
  63. }
  64.  
  65. public partial class OnsiteCourse : Course
  66. {
  67. public OnsiteCourse()
  68. {
  69. Details = new Details();
  70. }
  71.  
  72. public Details Details { get; set; }
  73. }
  74.  
  75. public class Details
  76. {
  77. public System.DateTime Time { get; set; }
  78. public string Location { get; set; }
  79. public string Days { get; set; }
  80. }
  81.  
  82. public class Instructor
  83. {
  84. public Instructor()
  85. {
  86. this.Courses = new List<Course>();
  87. }
  88.  
  89. // Primary key
  90. public int InstructorID { get; set; }
  91. public string LastName { get; set; }
  92. public string FirstName { get; set; }
  93. public System.DateTime HireDate { get; set; }
  94.  
  95. // Navigation properties
  96. public virtual ICollection<Course> Courses { get; private set; }
  97. }
  98.  
  99. public class OfficeAssignment
  100. {
  101. // Specifying InstructorID as a primary
  102. [Key()]
  103. public Int32 InstructorID { get; set; }
  104.  
  105. public string Location { get; set; }
  106.  
  107. // When the Entity Framework sees Timestamp attribute
  108. // it configures ConcurrencyCheck and DatabaseGeneratedPattern=Computed.
  109. [Timestamp]
  110. public Byte[] Timestamp { get; set; }
  111.  
  112. // Navigation property
  113. public virtual Instructor Instructor { get; set; }
  114. }
  1.  

转 Configuring Relationships with the Fluent API的更多相关文章

  1. [转]Entity Framework Fluent API - Configuring and Mapping Properties and Types

    本文转自:https://msdn.microsoft.com/en-us/data/jj591617#1.2 When working with Entity Framework Code Firs ...

  2. Entity Framework Code First (五)Fluent API - 配置关系

    上一篇文章我们讲解了如何用 Fluent API 来配置/映射属性和类型,本文将把重点放在其是如何配置关系的. 文中所使用代码如下 public class Student { public int ...

  3. Entity Framework Code First (五)Fluent API - 配置关系 转载 https://www.cnblogs.com/panchunting/p/entity-framework-code-first-fluent-api-configuring-relationships.html

    上一篇文章我们讲解了如何用 Fluent API 来配置/映射属性和类型,本文将把重点放在其是如何配置关系的. 文中所使用代码如下 public class Student { public int ...

  4. 1.【使用EF Code-First方式和Fluent API来探讨EF中的关系】

    原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/relationship-in-entity-framework-using-code-firs ...

  5. 8.Fluent API in Code-First【Code-First系列】

    在前面的章节中,我们已经看到了各种不同的数据注解特性.现在我们来学习一下Fluent API. Fluent API是另外一种配置领域类的方式,它提供了更多的配置相比数据注解特性. Mappings[ ...

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

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

  7. EF Code-First 学习之旅 Fluent API

    Mappings To Database Model-wide Mapping Set default Schema Set Custom Convetions Entity Mapping To S ...

  8. Entity Framework Code-First(10):Fluent API

    Fluent API in Code-First: We have seen different DataAnnotations attributes in the previous sections ...

  9. EF里的默认映射以及如何使用Data Annotations和Fluent API配置数据库的映射

    I.EF里的默认映射 上篇文章演示的通过定义实体类就可以自动生成数据库,并且EF自动设置了数据库的主键.外键以及表名和字段的类型等,这就是EF里的默认映射.具体分为: 数据库映射:Code First ...

随机推荐

  1. asp.net core 创建允许跨域请求的api, cors.

    配置应用方域名. 在webapi中引用cors包,在startup的Configure\ConfigServices中增加启动项配置,在api中增加EnableCors的Attribute属性.即可. ...

  2. B - Alyona and towers CodeForces - 739C

    链接: https://vjudge.net/contest/202699#problem/B 题意: 给出一个序列,要支持区间加和操作 求其中最长的区间,该区间内的元素满足(ai<ai+1&l ...

  3. CentOS7.5安装nodejs 转

    CentOS7.5安装nodejs CentOS安装NodeJS 在CentOS下安装NodeJS有以下几种方法.使用的CentOS版本为7.2.CentOS其他版本的NodeJS安装大同小异,也可以 ...

  4. ubuntu系统查看已安装的软件

    1.查看安装的所有软件 dpkg -l 例如:dpkg -l | grep ftp 2.查看软件安装的路径 dpkg -L | grep ftp 也可以用 whereis ftp 3.查看软件版本 a ...

  5. Codeforces 425E Sereja and Sets dp

    Sereja and Sets 我们先考虑对于一堆线段我们怎么求最大的不相交的线段数量. 我们先按 r 排序, 然后能选就选. 所以我们能想到我们用$dp[ i ][ j ]$表示已经选了 i 个线段 ...

  6. String str = new String("xyz") 会创建几个对象

    转载:https://blog.csdn.net/andychen314/article/details/50857313 答案是 两个对象,要理解这个,就要知道string类的工作原理.下面来慢慢分 ...

  7. Excel ——多表关联查询-vlookup

    一.分组 需求: 在B列的右侧添加一列[消费分组]对B列的[月分组水平]进行分组,原始数据如下: 公式:在 C2 输入:“=VLOOKUP(B2,$E$1:$G$4,2,1)”,下拉填充. 提示:VL ...

  8. Spring日记_02之搭建一个新项目

    程序 表现层 业务层 持久层 从持久层开始写 总结如何搭建一个项目 1.新建一个Maven项目 2.可能新建之后会有错,右键Deployment Descriptor: note, 选择Generat ...

  9. mybatis提示Invalid bound statement (not found)错误的可能原因

    https://www.cnblogs.com/liaojie970/p/8034525.html

  10. CentOS 通过yum在线安装MySQL5.7

    CentOS 通过yum在线安装MySQL5.7 Step1: 检测系统是否自带安装mysql # yum list installed | grep mysql Step2: 删除系统自带的mysq ...