简体   繁体   中英

EF Code first: Insert Many to many

A post can have many Topics. A topic can be assigned to many posts. When adding a post with two topics selected from topic list, two NULL topics also inserted to my topic table. See Id=34 and 35 . What did I do wrong? Topics should not be changed. I am adding a new post and selecting topics from fixed number of topics (a dropdownlist). It is keep tracked in PostTopics table (PostID, TopicID).

Topics table:

 Id TopicName TopicDesc 31 Sports Sports 32 Game Game 33 Politics Politics 34 NULL NULL 35 NULL NULL 

TopicPosts table:

Topic_Id    Post_Id
34  11
35  11


public class Post
{
    public int Id { get; set; }
    public int UserId { get; set; }

    public virtual ICollection<Topic> PostTopics { get; set; }

}


public class Topic
{
    public int Id { get; set; }
    public string TopicName { get; set; }

    public virtual ICollection<Request> Requests { get; set; }

}

// insert code: I think the problem is here

  using (var context = new ChatContext())
  {
             // Post
             context.Posts.Add(pobjPost);

             pobjPost.PostTopics = new List<Topic>();
             // topics
             foreach (var i in pobjTopics)
             {

             pobjPost.PostTopics.Add(i);
             }

             context.SaveChanges();
   }

You must attach the topics first to the context to put them into state Unchanged and tell EF that they are already existing in the database. Otherwise EF will assume that the topics are new and insert them into the database. After that you can add the post to the context so that the post can be inserted as a new entity into the database together with the relationship records in the many-to-many join table:

using (var context = new ChatContext())
{
    pobjPost.PostTopics = new List<Topic>();
    foreach (var pobjTopic in pobjTopics)
    {
        context.Topics.Attach(pobjTopic); // topic is in state Unchanged now
        pobjPost.PostTopics.Add(pobjTopic);
    }
    context.Posts.Add(pobjPost); // post in state Added, topics still Unchanged
    context.SaveChanges();
}

To create a relationship, both relating objects should be attached into the context first.

Try this way:

using (var context = new ChatContext())
      {
                 // Post
                 context.Posts.Attach(pobjPost);

                 pobjPost.PostTopics = new List<Topic>();
                 // topics
                 foreach (var i in pobjTopics)
                 {

                 pobjPost.PostTopics.Add(i);
                 }

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