I have 3 Tables with many-to-many relationaship
Questions - (QuestionId, Question)
Tags - (TagId, TagName)
QuestionTag - (QuestionId, TagId)
I have a scenario where users ask questions and they can add related tags to it.
Later if they need to add some new tag(which is already in the database) for the existing questing, How to do it? I need to add only the questionId and TagId into "QuestionTag" table without adding new question or tag as they are already added in the table. How to do it?
I found a similar question at the link Insert/Update Many to Many Entity Framework . How do I do it? which has the similar scenario where new question is added and tags which are already in the database are mapped.
using (var context = new MyContext())
{
var question= new Question { Question = "I have a question" };
Tag tag1 = context.Tags.FirstOrDefault(s => s.Name == "C#");
Tag tag2 = context.Tags.FirstOrDefault(s => s.Name == ".net");
question.Tags.Add(tag1);
question.Tags.Add(tag2);
context.AddToQuestiones(question);
context.SaveChanges();
}
So to work with my scenario, I modified the above code as
var question= context.Question.FirstOrDefault(q => q.QuestionId == 1);
But I got the following exception.
"The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects."
Also how delete the questiontag from "QuestionTag" for any question suppose if they are wrongly added with mismatch tag name.
Help me out to resolve this.