Entity Framework Configuring Relationships with the Fluent API

相关链接: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; }
}
时间: 2024-12-09 05:17:16

Entity Framework Configuring Relationships with the Fluent API的相关文章

[转]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 First the default behavior is to map your POCO classes to tables using a set of conventions baked into EF. Sometimes, however, you cannot or do not want t

Entity Framework Fluent API

Entity Framework Fluent API - Configuring/Mapping Properties & Types Skip to main content Data Developer Center Sign in United States (English) Home Library Learn Downloads Support Community Forums Documentation Videos Articles Books Hands-on Labs We

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

小分享:我有几张阿里云优惠券,用券购买或者升级阿里云相应产品最多可以优惠五折!领券地址:https://promotion.aliyun.com/ntms/act/ambassador/sharetouser.html?userCode=ohmepe03 上篇博文说过当我们定义的类不能遵循约定(Conventions)的时候,Code First 提供了两种方式来配置你的类:DataAnnotations 和 Fluent API, 本文将关注 Fluent API.  一般来说我们访问 Flu

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

上一篇文章我们讲解了如何用 Fluent API 来配置/映射属性和类型,本文将把重点放在其是如何配置关系的. 文中所使用代码如下 public class Student { public int ID { get; set; } public string Name { get; set; } public DateTime EnrollmentDate { get; set; } // Navigation properties public virtual Address Address

1.Relationship in Entity Framework Using Code First Approach With Fluent API【使用EF Code-First方式和Fluent API来探讨EF中的关系】

In this article, you will learn about relationships in Entity Framework using the Code First Approach with Fluent API. 在这篇文章中,你将会学习到使用EF Code-First方式和Fluent API来探讨EF中的关系(一对一,一对多,多对多). Introduction[介绍] A relationship, in the context of databases, is a

Entity Framework Code-First(10):Fluent API

Fluent API in Code-First: We have seen different DataAnnotations attributes in the previous sections to override default Code-First Conventions. Here, we will learn about Fluent API. Fluent API is another way to configure your domain classes. Fluent

Entity Framework 一次加载许多个 Fluent API 映射

可通过多种方法来指定模型的 Fluent 映射(从类到数据库). 1.直接在 DbContext 类的 OnModel­Creating 方法中进行映射,如下所示: protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<XsreAdminData>().Property(p => p.LoginTime).HasPrecision(18, 0); modelBu

Entity Framework 6 Recipes 2nd Edition(9-4)译-&gt;Web API 的客户端实现修改跟踪

9-4. Web API 的客户端实现修改跟踪 问题 我们想通过客户端更新实体类,调用基于REST的Web API 服务实现把一个对象图的插入.删除和修改等数据库操作.此外, 我们想通过EF6的Code First方式实现对数据的访问. 本例,我们模拟一个N层场景,用单独的控制台应用程序作为客户端,调用Web API服务(web api项目). 注:每个层用一个单独的解决方案,这样有助于调试和模拟N层应用. 解决方案 假设我们一个如Figure 9-4.所示模型 Figure 9-4. A 客户

Entity Framework 6 Recipes 2nd Edition(9-3)译-&gt;找出Web API中发生了什么变化

9-3. 找出Web API中发生了什么变化 问题 想通过基于REST的Web API服务对数据库进行插入,删除和修改对象图,而不必为每个实体类编写单独的更新方法. 此外, 用EF6的Code Frist实现数据访问管理. 本例,我们模拟一个N层场景,用单独的客户端(控制台应用)来调用单独的基于REST服务的Web网站(WEB API应用) . 注意:每层使用单独的Visual Studio 解决方案, 这样更方便配置.调试和模拟一个N层应用. 假设有一个如Figure 9-3所示的旅行社和预订