简体   繁体   中英

Many-to-many relations in Entity Framework

I have an issue with many-to-many relations.

I have 3 model classes:

  1. Article - >>> Item
  2. Keyword - >>> Keyword
  3. TableForRelation between Articles And Keywords - >>> ItemKeywords

With Entity Framework Core, I write these 3 classes and they work fine

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; }
}

Question is: how can I tell Entity Framework if Keyword exists do not put that in keyword table and just create a relation to that in ItemKeywords table.

database uml

before to add a KeyWord to Item.ItemKeyWords you have to try to load it from context.Set<KeyWord>() .

If the load results on a null, then do as actually.

If the load != null then add the loaded value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM