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加载单个属性

相关文章
相关标签/搜索