需要这方面的帮助。我需要在控制器操作中将会话中的一些数据保存到数据库。但是我在 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();
}
}
}