私はおそらく愚かな間違いを犯していますが、なぜこれが起こっているのか理解できません。最初は個人情報を保存しているため、質問テーブルに行が作成されますが、質問を更新すると、質問テーブルに新しい行が作成され、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");
}