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);
source share