ความสัมพันธ์แบบกลุ่มต่อกลุ่มใน Entity Framework

ฉันมีปัญหากับความสัมพันธ์แบบกลุ่มต่อกลุ่ม

ฉันมี 3 คลาสโมเดล:

  1. บทความ - >>> รายการ
  2. คำหลัก - >>> คำหลัก
  3. TableForRelation ระหว่างบทความและคำหลัก - >>> ItemKeywords

ด้วย Entity Framework Core ฉันเขียน 3 คลาสนี้และทำงานได้ดี

public class Item
{
      public int Id { get; set; }
      public string Content { get; set; }

      public virtual ICollection<ItemKeyWords> ItemKeyWords { get; set; }
}

public class KeyWord
{
       public int Id { get; set }
       public string Text { get; set; }

       public virtual  ICollection<ItemKeyWords> ItemKeyWords { get; set; }
}

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

        public int ItemId { get; set; }
        public virtual Item Item { get; set; }

        public int KeyWordId { get; set; }
        public virtual KeyWord KeyWord { get; set; }
}

คำถามคือ: ฉันจะบอก Entity Framework ได้อย่างไรหากมี Keyword อยู่ อย่าใส่สิ่งนั้นลงในตารางคำหลักและเพียงสร้างความสัมพันธ์กับสิ่งนั้นในตาราง ItemKeywords

uml ฐานข้อมูล


person soroushdes    schedule 26.04.2017    source แหล่งที่มา


คำตอบ (1)


ก่อนที่จะเพิ่ม KeyWord ไปยัง Item.ItemKeyWords คุณต้องลองโหลดจาก context.Set<KeyWord>()

หากผลการโหลดเป็นโมฆะ ให้ทำตามจริง

หาก load != null ให้เพิ่มค่าที่โหลด

person tschmit007    schedule 26.04.2017
comment
ฉันทำอย่างนั้นและทำงานให้ฉัน .thx มีวิธีใดที่ดีกว่านี้ไหม - person soroushdes; 26.04.2017
comment
หากคุณทราบรหัสของคำหลัก คุณสามารถใช้รหัสนั้นเพื่อสร้างเอนทิตีของคำหลักและแนบไปกับบริบทได้ จากนั้นคุณใช้เอนทิตีที่แนบมาเพื่อเพิ่มคำสำคัญลงในรายการ การทำเช่นนี้คุณจะหลีกเลี่ยงการโดนฐานข้อมูล - person tschmit007; 26.04.2017