實體框架 - 關係



在關係資料庫中,關係是透過外部索引鍵存在於關係資料庫表之間的一種情況。外部索引鍵 (FK) 是一個列或列的組合,用於建立和強制兩個表之間的資料鏈接。下圖包含三個表。

  • 學生
  • 課程
  • 註冊
Relational Database

在上圖中,您可以看到表之間存在某種關聯/關係。表之間存在三種關係型別,不同表之間的關係取決於相關列的定義方式。

  • 一對多關係
  • 多對多關係
  • 一對一關係

一對多關係

  • 一對多關係是最常見的關係型別。

  • 在這種型別的關係中,表 A 中的一行可以在表 B 中具有多行匹配行,但表 B 中的一行只能在表 A 中具有一個匹配行。

  • 外部索引鍵在表示關係多端的表中定義。

  • 例如,在上圖中,學生和登錄檔之間存在一對多關係,每個學生可以有多個註冊,但每個註冊只屬於一個學生。

在實體框架中,這些關係也可以用程式碼建立。以下是與一對多關係關聯的學生和註冊類的示例。

public class Student {
   public int ID { get; set; }
   public string LastName { get; set; }
   public string FirstMidName { get; set; }
   public DateTime EnrollmentDate { get; set; }
	
   public virtual ICollection<Enrollment> Enrollments { get; set; }
}

public class Enrollment {

   public int EnrollmentID { get; set; }
   public int CourseID { get; set; }
   public int StudentID { get; set; }
	
   public Grade? Grade { get; set; }
   public virtual Course Course { get; set; }
   public virtual Student Student { get; set; }
}

在上面的程式碼中,您可以看到 Student 類包含 Enrollment 的集合,但 Enrollment 類只有一個 Student 物件。

多對多關係

在多對多關係中,表 A 中的一行可以在表 B 中具有多行匹配行,反之亦然。

  • 您可以透過定義一個第三個表(稱為連線表)來建立這種關係,其主鍵由表 A 和表 B 的外部索引鍵組成。

  • 例如,學生和課程表之間存在多對多關係,該關係由這兩個表到登錄檔的每個表的一對多關係定義。

以下程式碼包含 Course 類和上面兩個類,即StudentEnrollment

public class Course {
   [DatabaseGenerated(DatabaseGeneratedOption.None)]
	
   public int CourseID { get; set; }
   public string Title { get; set; }
	
   public int Credits { get; set; } 
   public virtual ICollection<Enrollment> Enrollments { get; set; }
}

您可以看到 Course 類和 Student 類都具有 Enrollment 物件的集合,這使得透過連線類 Enrollment 形成多對多關係。

一對一關係

  • 在一對一關係中,表 A 中的一行在表 B 中最多隻能有一個匹配行,反之亦然。

  • 如果兩個相關列都是主鍵或具有唯一約束,則會建立一對一關係。

  • 在一對一關係中,主鍵還充當外部索引鍵,並且兩個表都沒有單獨的外部索引鍵列。

這種型別的關係並不常見,因為大多數以這種方式關聯的資訊都將位於一個表中。您可以使用一對一關係來 -

  • 將具有許多列的表分割。
  • 出於安全原因隔離表的一部分。
  • 儲存短暫的資料,可以透過簡單地刪除表來輕鬆刪除。
  • 儲存僅適用於主表子集的資訊。

以下程式碼用於新增另一個名為 StudentProfile 的類,其中包含學生的電子郵件 ID 和密碼。

public class Student {
   public int ID { get; set; }
   public string LastName { get; set; }
   public string FirstMidName { get; set; }
   public DateTime EnrollmentDate { get; set; }
	
   public virtual ICollection<Enrollment> Enrollments { get; set; }
   public virtual StudentProfile StudentProfile { get; set; }
}

public class StudentProfile {

   public StudentProfile() {}
   public int ID { get; set; }
   public string Email { get; set; }
   public string Password { get; set; }
	
   public virtual Student Student { get; set; }
}

您可以看到 Student 實體類包含 StudentProfile 導航屬性,而 StudentProfile 包含 Student 導航屬性。

每個學生只有一個電子郵件和密碼才能登入大學域。這些資訊可以新增到 Student 表中,但出於安全原因,它被分隔到另一個表中。

廣告