我可能犯了一个愚蠢的错误,但我不知道为什么会这样。我最初保存个人信息,这会在问题表中创建一行,但是当我去更新问题时,它会在问题表中创建一个新行并将 questionId 列更新为添加的新行。代码如下。
public class PersonalInfo
{
public virtual int PersonalInfoId { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual string Email { get; set; }
public virtual string CompanyName { get; set; }
public virtual string Gender { get; set; }
public virtual DateTime GenerationDate { get; set; }
[ForeignKey("Question")]
public int QuestionId { get; set; }
[ForeignKey("QuestionId")]
public virtual Question Question { get; set; }
public PersonalInfo()
{
if (Question == null)
Question = new Question();
}
}
public class Question
{
public virtual int QuestionId { get; set; }
public virtual string Question1 { get; set; }
public virtual string Question2 { get; set; }
public virtual string Question3 { get; set; }
public virtual string Question4 { get; set; }
public virtual string Question5 { get; set; }
public virtual string Question6 { get; set; }
public virtual string Question7 { get; set; }
public virtual string Question8 { get; set; }
public virtual string Question9 { get; set; }
public virtual string Question10 { get; set; }
public virtual string Question11 { get; set; }
public virtual string Question12 { get; set; }
}
并更新代码...
[HttpPost]
public ActionResult Questions(FormCollection form)
{
int id = GetCookie();
//var questions = db.Questions.Find(id);
var personalInfo = db.PersonalInfoes.Include(i => i.Question).SingleOrDefault(p => p.PersonalInfoId == id);
personalInfo.Question.Question1 = form["question1"];
personalInfo.Question.Question2 = form["question2"];
personalInfo.Question.Question3 = form["question3"];
personalInfo.Question.Question4 = form["question4"];
personalInfo.Question.Question5 = form["question5"];
personalInfo.Question.Question6 = form["question6"];
personalInfo.Question.Question7 = form["question7"];
personalInfo.Question.Question8 = form["question8"];
personalInfo.Question.Question9 = form["question9"];
personalInfo.Question.Question10 = form["question10"];
personalInfo.Question.Question11 = form["question11"];
personalInfo.Question.Question12 = form["question12"];
db.SaveChanges();
return RedirectToAction("list");
}