Ef core中,定義實體類間的關係與它與表的映射形式!

學習 Ef core in actioin 的第2章總結:  格式較亂,本身懂數組

1、 1 對  0,1 的關係 :

類型 書       書的價格商
說明

一個純類學習

先存在,主實體spa

有一個外鍵3d

後產生的類,有外鍵,依賴主實體blog

代碼 

public class Book ci

{get

public int BookId { get; set; }  
public string Title { get; set; }
...........
public PriceOffer Promotion { get; set; }string

我覺得,不須要上面這句it

}io

public class PriceOffer 

{

public int PriceOfferId { get; set; }
public decimal NewPrice { get; set; }
public string PromotionalText { get; set; }
public int BookId { get; set; } //#b

 public Book Book{get;set;} //我覺得

}

反思:  我認爲價格商表是從表,上表格中紅色的句子,它應該有一個Book的導航屬性就對了, 

可是做者是反其道而行之。  在從類裏寫一個外鍵屬性!

這兩種寫法,生成的庫表同樣: 

 

,可是生成遷移語句能夠看到:

它們的區別在EF CORE的刪除行爲一節中有說明:  感受做者的寫法是正確的!

2、1  對   0,* 的關係

類型 書       書的 審覈人
說明

一個純類

先存在,主實體

有一個外鍵

後產生的類,有外鍵,依賴主實體

代碼 

public class Book 

{

public int BookId { get; set; }  
public string Title { get; set; }
...........
public ICollection<Review> Reviews { get; set; }

}

   public class Review                      //#L
    {
        public int ReviewId { get; set; }
        public string VoterName { get; set; }
        public int NumStars { get; set; }
        public string Comment { get; set; }

         public int BookId { get; set; }       //#M
    }

行爲和1對1是同樣的,只是導航屬性寫成 ICollection<Review>,  刪除行爲也是Cascade.

三,多 對 多的關係 

類型 書       書的 做者 關係表
說明

一個純類

先存在,主實體

一個純類

主實體

 
代碼 

public class Book 

{

public int BookId { get; set; }  
public string Title { get; set; }
...........
public ICollection<BookAuthor> 
            AuthorsLink { get; set; }   

}

    public class Author                          //#E
    {
        public int AuthorId { get; set; }
        public string Name { get; set; }

     

        public ICollection<BookAuthor> 
            BooksLink { get; set; }  
         
    }

    public class BookAuthor                    //#G
    {
        public int BookId { get; set; }        //#H
        public int AuthorId { get; set; }      //#H
        public byte Order { get; set; }        //#I

        public Book Book { get; set; }        
        public Author Author { get; set; }  

    }

生成的庫表:

4、顯示加載屬性

              db.Authors.Include(p => p.BooksLink)

     collection 加載數組屬性    reference加載單個屬性

相關文章
相關標籤/搜索