簡體   English   中英

"如何在 Entity Framework Core 中定義外鍵"

[英]How to define foreign Key in Entity Framework Core

我正在嘗試實現下表結構,但出現錯誤“不能用作實體類型的屬性,因為它被配置為導航。”

誰能幫我。

類別:<\/strong>

ID<\/th> 名稱<\/th><\/tr><\/thead>
1<\/td> 貓1<\/td><\/tr>
2<\/td> 貓2<\/td><\/tr>
3<\/td> 三類<\/td><\/tr>
4<\/td> 第四類<\/td><\/tr><\/tbody><\/table>

子類別:<\/strong>

ID<\/th> 類別 ID<\/th> 名稱<\/th><\/tr><\/thead>
1<\/td> 1<\/td> 子類 1<\/td><\/tr>
2<\/td> 1<\/td> 子類 2<\/td><\/tr>
3<\/td> 1<\/td> 子類 3<\/td><\/tr>
1<\/td> 2<\/td> 子類 4<\/td><\/tr>
1<\/td> 3<\/td> 子類5<\/td><\/tr>
2<\/td> 3<\/td> 子類6<\/td><\/tr><\/tbody><\/table>

物品:<\/strong>

ID<\/th> 類別 ID<\/th> 子類別 ID<\/th> 名稱<\/th><\/tr><\/thead>
1<\/td> 1<\/td> 2<\/td> 項目1<\/td><\/tr>
2<\/td> 3<\/td> 2<\/td> 項目2<\/td><\/tr>
3<\/td> 1<\/td> 空值<\/td> 第 3 項<\/td><\/tr>
4<\/td> 4<\/td> 空值<\/td> 第 4 項<\/td><\/tr><\/tbody><\/table>
public class Category { [Key] public int Id { get; set; } [Required] public string Name { get; set; } public virtual ICollection<HrCodeSubType> SubCategories { get; set; } } public class SubCategory { [Key] public int Id { get; set; } [ForeignKey("Category")] public int CategoryId { get; set; } public virtual Category Category { get; set; } [Required] public string Name { get; set; } } public class Item { [Key] public int Id { get; set; } [Required] public string Name { get; set; } [ForeignKey("Category")] public int CategoryId { get; set; } public virtual Category Category{ get; set; } public int? SubCategoryId { get; set; } public virtual SubCategory SubCategory { get; set; } }<\/code><\/pre>

流利的 API<\/strong>

在項目類中只保留子類別,因為它已經依賴於類別並且具有一對一的關系

public class Item
{
    [Key]
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    
    public int? SubCategoryId { get; set; }
    public virtual SubCategory SubCategory { get; set; }
  }

暫無
暫無

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

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