Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6011677
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T02:17:40+00:00 2026-05-23T02:17:40+00:00

I am having trouble understanding if I am doing this correctly or not. I

  • 0

I am having trouble understanding if I am doing this correctly or not. I have 3 entities that are dependent on each other. I am trying to add new objects to these entities and then call save changes ultimately adding the corresponding records to the tables honoring the FK constraints.

I am getting the error:

The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.

enter image description here

In my code I am parsing some XML with linq while adding the new objects to the context as I go. In my service layer I have the following method to handle processing the incoming data.

public void ProcessSurvey(int surveyContentId, int caseNo, string surveyTitle, string reportVersion, string reportXml)
{
    // get surveyid 
    var surveyContent = _surveyContentRepository.GetSurveyContent(surveyContentId);
    // create response obj
    var surveyResponse = new SurveyResponse()
    {
        SurveyId = surveyContent.SurveyId,
        CaseNo = caseNo,
        SurveyTitle = surveyTitle,
        ReportVersion = reportVersion,
        Created = DateTime.Now,
        ResponseXML = reportXml
    };
    // add response obj to context?
    _surveyResponseRepository.Add(surveyResponse);
    // get the questions elements from the xml data
    var questions = SurveyResponseHelper.GetResponseQuestions(reportXml);
    // iterate over questions
    foreach (XElement question in questions)
        {
        SurveyQuestion thisSurveyQuestion = SurveyResponseHelper.ProcSurveyQuestion(question, surveyContentId);
        // add question?
        _surveyQuestionRepository.Add(thisSurveyQuestion);
        // get question answer
        SurveyAnswer thisSurveyAnswer = SurveyResponseHelper.GetAnswer(question);
        //update the answer with the question and response obj to satisfy the FK reference
        thisSurveyAnswer.SurveyQuestion = thisSurveyQuestion;
        thisSurveyAnswer.SurveyResponse = surveyResponse; // This is where it breaks ERRROR: The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects
        _surveyAnswerRepository.Add(thisSurveyAnswer);
        }
    //commit
    _surveyAnswerRepository.Save();
}

My Repositories look like this..

public interface ISurveyAnswerRepository
{
    void Add(SurveyAnswer surveyAnswer);
    void Save();
}
public class SurveyAnswerRepository : Repository, ISurveyAnswerRepository
{

    //private DiversionProgramsEntities _db;

    public SurveyAnswerRepository()
    {
        //_db = new DiversionProgramsEntities();
    }

    public void Add(SurveyAnswer surveyAnswer)
    {
        this.DataContext.SurveyAnswers.AddObject(surveyAnswer);


    }

    public void Save()
    {
        this.DataContext.SaveChanges();

    }

my base repository

public class Repository
{
    private DiversionProgramsEntities _dataContext;

    public DiversionProgramsEntities DataContext
    {
        get { return _dataContext ?? (_dataContext = DatabaseFactory.CreateContext()); }
    }


}

and static class / method to create the context

public static class DatabaseFactory
{

    public static DiversionProgramsEntities CreateContext()
    {
        return new DiversionProgramsEntities();
    }

}

here is my helper code..

public class SurveyResponseHelper
{
public static IEnumerable<XElement> GetResponseQuestions(string xmlResponseData)
{
    XElement xmlData = XElement.Parse(xmlResponseData);
    var questions = from n in xmlData.Descendants()
                    where n.Parent.Name.LocalName == "questions"
                    select n;

    return questions;
}

public static SurveyQuestion ProcSurveyQuestion(XElement question, int surveyContentId)
{
    // get the question type
    var questionType = question.Name.LocalName;
    // get question element text. This is the actual question text
    var questionText = question.Elements().Where(e => e.Name.LocalName == "direction").SingleOrDefault().Value;
    // check to see if this question exists in the data table, if it does then we will use the questionid from that which will get used to tie the SurveyAnswer to this question.
    // if question does not already exist then a new one will be created
    SurveyQuestionRepository surveyQuestionRepository = new SurveyQuestionRepository();
    SurveyQuestion surveyQuestion;
    surveyQuestion = surveyQuestionRepository.GetSurveyQuestion(surveyContentId, questionType, questionText);
    if (surveyQuestion == null)
    {
        surveyQuestion = new SurveyQuestion()
        {
            QuestionText = questionText,
            QuestionType = questionType,
            SurveyContentId = surveyContentId
        };
    }

    return surveyQuestion;
}

public static SurveyAnswer GetAnswer(XElement question)
{
    // get the answer index value
    var answers = question.Elements().Where(e => e.Name.LocalName == "answers").SingleOrDefault();
    int userAnswerIndex = Int32.Parse(answers.Attribute("userAnswerIndex").Value);
    // move the answers to an array so we can use the index to get the correct answer
    XElement[] answersArray = answers.Elements().ToArray();
    SurveyAnswer answer = new SurveyAnswer()
    {
        AnswerText = answersArray[userAnswerIndex].Value
    };

    return answer;
}



}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T02:17:41+00:00Added an answer on May 23, 2026 at 2:17 am

    As @TimHoolihan stated the issue is that you are not using the same Data Context for accessing the Survey Responses and Survey Questions and actually I believe the issue lines in the line below from the ProcSurveyQuestion method.

        SurveyQuestionRepository surveyQuestionRepository = new SurveyQuestionRepository();
    

    I see that you have a singleton DataContext in the DiversionProgramsEntities class, but I cannot infer from your code if the SurveyQuestionRepository and SurveryResponseRepositories are also using that same context. Based on the error you are getting, I am guessing that they are using separate contexts, so again as @TimHoolihan suggested, you need to modify your code to use the same context for both.

    You should also look into the UnitOfWork pattern as this is what you are trying to accomplish here, but you do not have a common context to track all of your changes across.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm having trouble understanding this question, and the explanation of the answer for an
I am having trouble understanding how layering is performed within Xcode. I have a
I'm having trouble understanding the following bit of code that I was hoping would
I'm having a lot of trouble doing something very simple. I have a viewController
I have been doing a bit of research on this but, I am having
Ok, I'm having trouble finding an answer to this that isn't just use JSON
I'm a former PHP developer now doing WPF/C# applications, and am having trouble understanding
I'm having trouble understanding what this means, and how it was coded Foo number
I'm having trouble understanding why a WSDL would be so beneficial, when the truth
I am having trouble understanding how the System Registry can help me convert a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.