0

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 !

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
BPruvost
  • 503
  • 2
  • 5
  • 16
  • BLL is a folder in which I have put "business" classes (BLL = Business Logic Layer), like Questionnaires.cs and Users.cs – BPruvost May 07 '12 at 15:14

1 Answers1

0

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

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Yes it does. Basically, what this method does is read from a session variable the ID of the questionnaire being taken, then goes into the database to get the "Questionnaire" object (using a objectcontext) and returns it. But I don't understand because even if questionnaire is handled with another object context, in the end the object I handle is user_questionnaire, and this one isn't used with another objectcontext. Anyway, what should I do then ? – BPruvost May 07 '12 at 15:18
  • 1
    @Tahedoz: `uq` references `q` from the other context. You should modify your BLL to work with an existing context. – SLaks May 07 '12 at 15:20