Search code examples
c#asp.netentity-frameworkobjectcontext

InvalidOperationException because of different ObjectContext objects


I'm facing an issue I don't really understand with Entity Manager (C#). I'm kinda new at this stuff so please bear with my noobness ^^

I'm trying to create an instance of UserQuestion (which makes the link in the DataBase between the tables UserQuestionnaire and Question ; UserQuestionnaire linking a User and a Questionnaire).

So here is the code in question :

public static void Insert_Resultat_Question_BDD(Question q, double resultat) {
     DataSourceContainer bdd = new DataSourceContainer(); // initializes the Context
     User user = BLL.Users.Get_User_Connecté(); // Gets the connected user
     Questionnaire questionnaire = BLL.Questionnaires.Get_Questionnaire_En_Cours(); // Gets the questionnaire being taken
     UserQuestionnaire user_questionnaire = bdd.UserQuestionnaireSet.FirstOrDefault(i => i.User.id == user.id && i.Questionnaire.id == questionnaire.id); // Get the UserQuestionnaire object for the user and questionnaire above
     UserQuestion uq = new UserQuestion {  score = resultat * q.bareme, bareme = q.bareme, Question = q, UserQuestionnaire = user_questionnaire }; // Creates the object
     bdd.AddToUserQuestionSet(uq); // Add it to the table
     bdd.SaveChanges(); // Save
 }

I'm getting an error when creating the UserQuestion, because the UserQuestionnaire = user_questionnaire statement launches an InvalidOperationException because : "The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects."

What I don't understand is that I only use 1 context ! (First line in the code I shared)

Can someone help me through this ? I don't really know what more to do :s

Thanks !


Solution

  • It sounds like BLL.Questionnaires.Get_Questionnaire_En_Cours() uses its own ObjectContext.