EF Code first: Insert Many to many

我的未来我决定 提交于 2019-12-20 02:08:28

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/11551760/ef-code-first-insert-many-to-many

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!