EF Core構建表的三種關係
關係型資料庫有三種表關係分別為:一對一, 一對多, 多對多
現在開發模式一般遵循CodeFirst就是通過實體讓EF Core生成SQL語句自動幫我們建立資料庫以及表關係,具體什麼原因自己百度一下哈哈哈哈!
廢話不多說我這裡直接上三種表型別(一對一, 一對多, 多對多)通過EF Core怎麼實現!
1.一對一
表:Husband(老公表) Wife(老婆表)一般情況下夫妻的關係是一對一的 ,特殊情況下除外 嘎嘎嘎!
程式碼示例:
internal class Husband { public int Id { get; set; } public stringHusbandName { get; set; } public Wife Wife { get; set; } }
internal class Wife { public int Id { get; set; } public string WifeName { get; set; } public Husband Husband { get; set; } public int HusbandId { get; set; } }
一對一的話,我們需要相互指向對方 Husband包含 Wife ,同時 Wife也包含Husband 因為在這是一對一所以需要都包含嘛,除此之外我們需要在任意一張表裡新增一個外來鍵自動來表示指向的模型,這樣一個簡單的一對一關係就搞定了
當然你如果不放心,你也可以建一個配置類,手動指明他們的關係,程式碼如下:
internal class HusbandConfig : IEntityTypeConfiguration<Husband> { public void Configure(EntityTypeBuilder<Husband> builder) { builder.HasOne(x => x.Wife).WithOne(x => x.Husband).HasForeignKey<Wife>(x => x.HusbandId); } }
2.一對多
一對多,我以文章和評論的關係來演示,畢竟一個文章對應多個評論 哈哈哈 ,(廢話.JPG)我現在寫的文章沒有評論!知道真相的我眼淚掉下來!
文章表:Article 評論表:Comment
一對多我們怎麼建立外來鍵,一般情況下我們的外來鍵指定在關係為一上,在這裡我們就可以外來鍵於Article ,因為在這他的關係是一
程式碼示例:
一個文章表裡有N條評論Article實體中用集合指明即可
internal class Article { public Article() { Comments = new List<Comment>(); } public int Id { get; set; } public string Title { get; set; } public string author { get; set; } ICollection<Comment> Comments{ get; set; } }
外來鍵一般建立在關係為一的主表上,我們直接在Comment 表裡新增Article欄位即表示外來鍵於主表
internal class Comment { public int Id { get; set; } public string Content { get; set; } public Article Article { get; set; } }
當然你如果不放心,你也可以建一個配置類,手動指明他們的關係,程式碼如下:
internal class ArticleConfig : IEntityTypeConfiguration<Article> { public void Configure(EntityTypeBuilder<Article> builder) { builder.HasMany(x => x.Comments).WithOne(x => x.Article); } }
2.多對多 以學生與老師舉例,一個老師對應N個學生,同理一個學生也對應N個老師!
多對多的關係怎麼外來鍵都不合適,無從下手的感覺,所以就要用到第三張表來建立關係。我們先建立Teacher 和Student 看看怎麼在EF Core中指定多對多關係吧!
學生表包含多個老師也是用集合欄位表示(多對多)
internal class Student { public Student() { Teachers = new List<Teacher>(); } public int Id { get; set; } public string Name { get; set; } public int Sex { get; set; } public ICollection<Teacher> Teachers { get; set; } }
老師表包含多個學生也是用集合欄位表示(多對多)
public Teacher() { Students = new List<Student>(); } public int Id { get; set; } public string TeacherName { get; set; } public int Sex { get; set; } public ICollection<Student> Students { get; set; }
如果當前直接執行資料遷移Add-Migration xxx 並儲存到資料庫Update-Database -v(-v表示顯示詳情資訊)的話,EF Core會預設給我們生成一張第三張關係表 名字一般是兩張表的名字例(StudentTeacher)
如果要指定生成的第三張表名,我們需要在配置類中指定,程式碼如下:
internal class StudentConfig : IEntityTypeConfiguration<Student> { public void Configure(EntityTypeBuilder<Student> builder) { builder.HasMany(x => x.Teachers).WithMany(x => x.Students).UsingEntity(x => x.ToTable("Student_Teacher")); } }
這樣就可以指定EF Coro在建立第三張關係表生成自己指定的名稱了!
這是最近複習基礎知識的筆記,如果能幫助到您!真的很開心!
三更燈火五更雞,正是男兒讀書時!