簡體   English   中英

實體框架弄亂了我的多對多自我關系

[英]Entity Framework messes up my many-to-many self relation

我有一個產品表和一個BundleLink表,它們定義了哪個產品是另一個產品的捆綁產品。

    public class Product
    {
        public int Id { get; set; }

        public ICollection<BundleLink> MasterOf { get; set; }

        public ICollection<BundleLink> BundleOf { get; set; }
    }

    public class BundleLink
    {
        public int Id { get; set; }

        public Product Master { get; set; }

        public Product Bundle { get; set; }

        public int Quantity { get; set; }
    }

因此,當我使用主產品時,我會看到捆綁在指什么產品,以及其他方向。

但是實體框架在BundleLink表的sql服務器中創建4列。 它為我定義的產品字段創建一個,再創建兩個外鍵,其中每個外鍵每次都為null,這取決於我添加捆綁的方向。 如何為EF定義哪個BundeLink集合屬於哪個產品?

我希望我的描述是可以理解的。 提前致謝。

在實體框架中,您需要遵循EF 6和EF Core中的數據注釋-ForeignKey屬性。

ForeignKey屬性用於在EF 6和EF Core中的兩個實體之間的關系中配置外鍵。 它會覆蓋默認約定。 根據默認約定,當EF的名稱與相關實體的主鍵屬性匹配時,EF會將其作為外鍵屬性。

詳細信息: http : //www.entityframeworktutorial.net/code-first/foreignkey-dataannotations-attribute-in-code-first.aspx

謝謝raghu

如何為EF定義哪個BundeLink集合屬於哪個產品?

您有兩種解決方案:

  • OnModelCreating你的方法DbConext用流利的配置,以便通過定義關系有助於EF知道哪些集合屬於哪個。
  • InverseProperty屬性裝飾您的收藏集。 因此,在你的收藏,你將有InversProperty("Master")MasterOf收集和InversProperty("Bundle")BundleOf

暫無
暫無

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

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