これについて助けが必要です。コントローラのアクションで、セッション中のデータをDBに保存する必要があります。しかし、answer.Add(answer);で「C#のIEntityChangeTrackerの複数のインスタンスでエンティティオブジェクトを参照できません」というエラーが発生します。
誰かがこれで私を助けることができますか?
Questionare questionare = unitOfWork.QuestionareRepository.GetByID(id);
SADEntitiesContext db = new SADEntitiesContext();
foreach (Question question in questionare.Questions)
{
//check if there are data in Session and save it
_question = "question"+question.QuestionID.ToString();
if (Session[_question] != null)
{
var answer = new Answers();
if (TryUpdateModel(answer))
{
questionanswer = (QuestionAnswerData)Session[_question];
int qID = Int16.Parse(questionanswer.QuestionID);
var answertoupdate = answer.GetAnswer(qID, questionanswer.UserID, questionanswer.EmployeID);
//db.Answers.Remove(answertoupdate);
answer.UserName = questionanswer.UserID;
answer.Answer = db.AnswerChoices.Find(Int16.Parse(questionanswer.AnswerID));
answer.AnsweredAt = DateTime.Now;
answer.locked = false;
answer.Question = question;
answer.Questionare = questionare;
if (questionanswer.EmployeID != null)
{
answer.AnswerAboutUser = questionanswer.EmployeID;
}
if (answertoupdate != null)
{
answertoupdate = answer;
ok = (answertoupdate.Save() > 0);
}
else
{
answer.Add(answer);
ok = (answer.Save() > 0);
}
}
}
回答クラスパブリッククラス回答{
SADEntitiesContext db = new SADEntitiesContext();
public int AnswersId { get; set; }
//[Display(Name = "DataResposta", ResourceType = typeof(Resources))]
public DateTime AnsweredAt { get; set; }
//[Display(Name = "bloqueado", ResourceType = typeof(Resources))]
public bool locked { get; set; }
// [Display(Name = "UserName", ResourceType = typeof(Resources))]
public string UserName { get; set; }
//[Display(Name = "AnswersAboutUser", ResourceType = typeof(Resources))]
public string AnswerAboutUser { get; set; }
//[Display(Name = "Resposta", ResourceType = typeof(Resources))]
public virtual AnswerChoices Answer { get; set; }
//[Display(Name = "Questionare", ResourceType = typeof(Resources))]
public virtual Questionare Questionare { get; set; }
//[Display(Name = "QuestionID", ResourceType = typeof(Resources))]
public virtual Question Question { get; set; }
//
// Persistence
public int Save()
{
return db.SaveChanges();
}
public Answers GetAnswer(int questionID, string employeID, string userID)
{
return db.Answers
.Where(e => e.UserName == userID
&& e.Question.QuestionID == questionID
&& e.AnswerAboutUser == employeID)
.FirstOrDefault();
}
public Answers GetAnswer(int id)
{
return db.Answers.SingleOrDefault(d => d.AnswersId == id);
}
//
// Insert/Delete Methods
public void Add(Answers _answer)
{
db.Answers.Add(_answer);
db.SaveChanges();
}
}
}