SQL Server Relationship With Entity Framework

2022-12-20

筆記 SQL Server Relationship 以及 Entity Framework 物件的對應關係。

SQL Server Logo

說明

使用 Entity Framework Tutorial 所設計的資料庫以及微軟範例資料庫 Northwind 與 Adventureworks 探討在 Database First 下,資料庫索引外鍵關聯性以及 Entity Framework 類別關聯的對應關係。

Relationship in EDMX
Relationship in SQL Server Diagram

1 to 0..1 relationship

Student (1)

  • StudentID (PK)
  • virtual StudentAddress StudentAddress

StudentAddress (0..1)

  • StudentID (PK, FK)
  • virtual Student Student

只存在 1 to 0..1 不存在 1 to 1 的情況。

1 to many relationship

Standard (0..1)

  • StandardId (PK)
  • ICollection Teacher

Teacher (*)

  • TeacherId (PK)
  • int? StandardId (FK)
  • virtual Standard Standard

Standard (0..1)

  • StandardId (PK)
  • ICollection Student

Student (*)

  • StudentID (PK)
  • int? StandardId (FK)
  • virtual Standard Standard

Teacher (0..1)

  • TeacherId (PK)
  • ICollection Course

Course

  • CourseId (PK)
  • int? TeacherId (FK)
  • virtual Teacher Teacher

只存在 0..1 to many 的情況,不存在 1 to many 的情況,如果有,是來自於 many to many 的衍生料表與兩端的存在。

many to many relationship

Course

  • CourseId (PK)
  • ICollection Student

Student (*)

  • StudentID (PK)
  • ICollection Course

StudentClass (Table but not Class)

  • CourseId (PK)
  • StudentID (PK)
  • StudentCourseCourseId to Course.CourseId (FK)
  • StudentCourseStudentId to Student.StudentId (FK)

參考資料

Entity Framework Tutorial