簡體   English   中英

在Entity Framework Core中對完全定義的關系存在誤解

[英]Misunderstanding with fully defined relationship in Entity Framework Core

我們來看看官方文檔中的示例:

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public BlogImage BlogImage { get; set; }
}

public class BlogImage
{
    public int BlogImageId { get; set; }
    public byte[] Image { get; set; }
    public string Caption { get; set; }

    public int BlogId { get; set; }
    public Blog Blog { get; set; }
} 

我們可以看到,我們已經完全定義了Blog和BlogImage之間的一對一關系,其中Blog是父級,而BlogImage是子級實體。

但是,如果我們看一下創建的表,則會看到以下標頭:

  • BlogId,博客網址
  • BlogImageId,圖片,標題,BlogId為BlogImage

我在BlogImage表中對這個BlogId有一些誤解,我們不應該在Blog表中定義BlogImageId外鍵,這是什么原因,在子實體中定義外鍵還是在父類中? 如果我們有一個孩子的千個父母,那么子實體中將有數千個外鍵! 很奇怪。

文檔只是以這種方式說明了一對一的關系,但這並不是唯一的方式。 你的思維方式也是正確的。 以下在EF中也是有效的一對一關系。

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
    public int BlogImageId { get; set; }
    public BlogImage BlogImage { get; set; }
}

public class BlogImage
{
    public int BlogImageId { get; set; }
    public byte[] Image { get; set; }
    public string Caption { get; set; }    
    public Blog Blog { get; set; }
} 

是的,對於確切的一對一關系,您應該使用此模型(您生成的表模式對應於一對多關系):

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }    
    public virtual BlogImage BlogImage { get; set; }
}
public class BlogImage
{
    [Key, ForeignKey("Blog")]
    public int BlogImageId { get; set; }

    public byte[] Image { get; set; }
    public string Caption { get; set; }

    public virtual Blog Blog { get; set; }
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM