EF code: insert many for many

A post can have many topics. A topic can be assigned to many posts. When adding a post with two topics selected from the list of topics, two NULL topics are also added to my topic table. See Id=34 and 35 . What have I done wrong? Themes should not be changed. I add a new message and select topics from a fixed number of topics (drop-down list). It is tracked in the PostTopics table (PostID, TopicID).

The table of topics:

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

The table of topics:

 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(); } 
+4
source share
2 answers

First you need to attach the topics to the context in order to put them in Unchanged state and tell EF that they already exist in the database. Otherwise, EF will assume that the topics are new and insert them into the database. After that, you can add the message to the context so that the message can be inserted as a new entity into the database along with the many-to-many relationship table entries:

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

To create a relationship, both related objects must first be context bound.

Try as follows:

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

All Articles