相关链接:Configuring Relationships with the Fluent API

Configuring a Required-to-Optional Relationship (One-to-Zero-or-One 1…0,1)

以下示例,表示1…0,1的关系。OfficeAssignment表有一个属性InstructorID,它是一个主键也是一个外键。

HasKey方法用于配置主键。

// Configure the primary key for the OfficeAssignment
modelBuilder.Entity<OfficeAssignment>() .HasKey(t => t.InstructorID); // Map one-to-zero or one relationship
modelBuilder.Entity<OfficeAssignment>() .HasRequired(t => t.Instructor) .WithOptional(t => t.OfficeAssignment);

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

// Configure the primary key for the OfficeAssignment
modelBuilder.Entity<OfficeAssignment>() .HasKey(t => t.InstructorID); modelBuilder.Entity<Instructor>() .HasRequired(t => t.OfficeAssignment) .WithRequiredPrincipal(t => t.Instructor);

Configuring a Many-to-Many Relationship

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

modelBuilder.Entity<Course>() .HasMany(t => t.Instructors) .WithMany(t => t.Courses) .Map(m => { m.ToTable("CourseInstructor"); m.MapLeftKey("CourseID"); m.MapRightKey("InstructorID"); });

Configuring a Relationship with One Navigation Property

// Configure the primary Key for the OfficeAssignment
modelBuilder.Entity<OfficeAssignment>() .HasKey(t => t.InstructorID); modelBuilder.Entity<Instructor>() .HasRequired(t => t.OfficeAssignment) .WithRequiredPrincipal();

Enabling Cascade Delete

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

Configuring a Composite Foreign Key

// Composite primary key
modelBuilder.Entity<Department>()
.HasKey(d => new { d.DepartmentID, d.Name }); // Composite foreign key
modelBuilder.Entity<Course>()  .HasRequired(c => c.Department)  .WithMany(d => d.Courses) .HasForeignKey(d => new { d.DepartmentID, d.DepartmentName });

Renaming a Foreign Key That Is Not Defined in the Model

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

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

modelBuilder.Entity<Course>() .HasRequired(c => c.Department) .WithMany(d => d.Courses) .HasForeignKey(c => c.SomeDepartmentID);

Model Used in Samples

using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
// add a reference to System.ComponentModel.DataAnnotations DLL
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System; public class SchoolEntities : DbContext
{ public DbSet<Course> Courses { get; set; } public DbSet<Department> Departments { get; set; } public DbSet<Instructor> Instructors { get; set; } public DbSet<OfficeAssignment> OfficeAssignments { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { // Configure Code First to ignore PluralizingTableName convention // If you keep this convention then the generated tables will have pluralized names. modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); }
} public class Department
{ public Department() { this.Courses = new HashSet<Course>(); } // Primary key public int DepartmentID { get; set; } public string Name { get; set; } public decimal Budget { get; set; } public System.DateTime StartDate { get; set; } public int? Administrator { get; set; } // Navigation property public virtual ICollection<Course> Courses { get; private set; }
} public class Course
{ public Course() { this.Instructors = new HashSet<Instructor>(); } // Primary key public int CourseID { get; set; } public string Title { get; set; } public int Credits { get; set; } // Foreign key public int DepartmentID { get; set; } // Navigation properties public virtual Department Department { get; set; } public virtual ICollection<Instructor> Instructors { get; private set; }
} public partial class OnlineCourse : Course
{ public string URL { get; set; }
} public partial class OnsiteCourse : Course
{ public OnsiteCourse() { Details = new Details(); } public Details Details { get; set; }
} public class Details
{ public System.DateTime Time { get; set; } public string Location { get; set; } public string Days { get; set; }
} public class Instructor
{ public Instructor() { this.Courses = new List<Course>(); } // Primary key public int InstructorID { get; set; } public string LastName { get; set; } public string FirstName { get; set; } public System.DateTime HireDate { get; set; } // Navigation properties public virtual ICollection<Course> Courses { get; private set; }
} public class OfficeAssignment
{ // Specifying InstructorID as a primary
    [Key()] public Int32 InstructorID { get; set; } public string Location { get; set; } // When the Entity Framework sees Timestamp attribute // it configures ConcurrencyCheck and DatabaseGeneratedPattern=Computed.
    [Timestamp] public Byte[] Timestamp { get; set; } // Navigation property public virtual Instructor Instructor { get; set; }
}

转载于:https://www.cnblogs.com/Currention/p/5288427.html

Entity Framework Configuring Relationships with the Fluent API相关推荐

  1. 使用Entity Framework Core,Swagger和Postman创建ASP.NET Core Web API的分步指南

    目录 介绍 背景 第1步:创建一个新项目 第2步:添加模型类 第3步:使用Entity Framework Core 第4步:添加数据库上下文和控制器 步骤5:在Package Manager控制台中 ...

  2. Entity Framework Fluent API - Relationships

    Entity Framework Fluent API - Relationships

  3. Entity Framework Fluent API

    原文:Entity Framework Fluent API 前言 使用DataAnnotation非常简单,但对于EntityFramework中的特性,就要在实体类中引入EntityFramewo ...

  4. Entity Framework Core 之Modeling Relationships

    Relationships (关系) 关系定义了两个实体之间的联系,在数据库关系中用外键约束来表示两个实体之间的联系.默认情况下若在模型类型中发现了导航属性就会创建关系.最常见的关系模式是导航属性定义 ...

  5. Entity Framework 6 Recipes 2nd Edition(9-1)译-用Web Api更新单独分离的实体

    第九章 在N层结构的应用程序中使用EF 不是所有的应用都能完全地写入到一个单个的过程中(就是驻留在一个单一的物理层中),实际上,在当今不断发展的网络世界,大量的应用程序的结构包含经典的表现层,应用程, ...

  6. What’s New in Entity Framework 4? API Changes(1)(转)

    If you have been working with the ADO.NET Entity Framework, you have probably been extremely eager t ...

  7. 全自动迁移数据库的实现 (Fluent NHibernate, Entity Framework Core)

    在开发涉及到数据库的程序时,常会遇到一开始设计的结构不能满足需求需要再添加新字段或新表的情况,这时就需要进行数据库迁移. 实现数据库迁移有很多种办法,从手动管理各个版本的ddl脚本,到实现自己的mig ...

  8. 使用Entity Framework和Web API的ASP.NET Core Blazor CRUD

    目录 介绍 背景 先决条件 使用代码 第1步--创建数据库和表 第2步--创建ASP.NET Core Blazor应用程序 ASP.NET Core Blazor解决方案的新增功能是什么? 客户端项 ...

  9. Entity Framework 基础

    一.什么是Entity Framework 微软官方提供的ORM工具,ORM让开发人员节省数据库访问的代码时间,将更多的时间放到业务逻辑层代码上.EF提供变更跟踪.唯一性约束.惰性加载.查询事物等.开 ...

  10. Code First :使用Entity. Framework编程(7) ----转发 收藏

    第7章 高级概念 The Code First modeling functionality that you have seen so far should be enough to get you ...

最新文章

  1. 高级软件工程第二次作业
  2. 开发日记-20190409 关键词 理想activity模型
  3. YY一下,扎克伯格做了一个什么样的AI家居助手?
  4. 一致性 Hash 算法学习(分布式或均衡算法)
  5. bzoj1679[Usaco2005 Jan]Moo Volume 牛的呼声*
  6. amd cpu不能在cmd环境下运行java代码_如何在Windows10中配置java的JDK环境
  7. 【转】SyntaxError: Non-ASCII character ‘\xe5′ in file
  8. 一般用css设置中文字体的Unicode编码
  9. java 难题_您可以避免的6种组织成长难题
  10. java file list listfiles,Java File listFiles()用法及代码示例
  11. C Tricks(五)—— 比例和阈值的实现
  12. PythonDay7
  13. office 2019 visio 2016安装
  14. html表格左边锁定,表头锁定
  15. Linux系统文件加密与解密应用
  16. 机器学习笔记 十五:随机森林(Random Forest)评估机器学习模型的特征重要性
  17. 如何寻找省级软件产业主管部门认可的软件检测机构出具报告
  18. python-线程池的使用
  19. String以及StringBuffer的基本操作
  20. 基于mindwave脑电波进行疲劳检测算法的设计(1)

热门文章

  1. python文件的路径_python3 文件及文件夹路径相关
  2. 【自然语言处理系列】预训练模型原理和实践综述 | 附汇报PPT原稿和18篇论文
  3. 代码整洁之道读书笔记----第三章---函数--第一节-专注且短小
  4. Playing Atari with Deep Reinforcement Learning 中文 讲解
  5. android studio for android learning (十二) 查看并获取联系人信息
  6. 【2019南昌邀请赛网络赛 J】Distance on the tree【边权树剖+主席树】
  7. 【线段树】Interval GCD【线段树维护gcd】
  8. VB 显示当前时间 24小时制
  9. LaTeX 长表格处理方法
  10. uni的numberbox怎么用_jQuery EasyUI表单插件Numberbox数字框