0

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.

Community
  • 1
  • 1
m rajesh
  • 15
  • 6

1 Answers1

0

Don't add the question to the context (with context.AddToQuestiones(question)), you are only changing a relationship and don't want to create a new entitiy in the database:

using (var context = new MyContext())
{
    Question question = context.Question.FirstOrDefault(q => q.QuestionId == 1);
    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.SaveChanges();
}

If you want to remove a tag load the question including the tags from the database and then remove the tag from the loaded collection:

using (var context = new MyContext())
{
    Question question = context.Question.Include("Tags")
        .FirstOrDefault(q => q.QuestionId == 1);

    // Retrieve the tag from the already loaded collection,
    // you don't need to query the DB again for the tag
    Tag tagToRemove = question.Tags.FirstOrDefault(s => s.Name == "C#");
    if (tagToRemove != null)
        question.Tags.Remove(tagToRemove);

    context.SaveChanges();
}

Make sure that you use the same context instance for loading the question and the tags. The exception you are having indicates that you are working with multiple different contexts.

Slauma
  • 175,098
  • 59
  • 401
  • 420