0
需要此幫助。 我需要將會話中的一些數據保存到數據庫控制器操作中。但我得到了「一個實體對象不能被C#中的IEntityChangeTracker的多個實例引用」的錯誤 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();
}
}
}
好的,去吧,從課堂上刪除所有東西,並使用控制器中相同的上下文來設置所有內容。 – user1622586