外部キーStudent、Loan、Bookに関連する3つのテーブルがあります。新しい学生を作成するときに、それをブックフォームテーブルBookに関連付けて、テーブルLoanにも保存できますが、既存の学生で編集した場合、変更はStudentに保存されません。テーブル。
StudentController.cs I
public ActionResult Create()
{
ViewBag.ISBN = new SelectList(db.Books, "ISBN", "Titulli");
return View();
}
//
// POST: /Student/Create
[HttpPost]
public ActionResult Create(Student student)
{
if (ModelState.IsValid)
{
db.Students.Add(student);
db.SaveChanges();
Loan l = new Loan()
{
StudentID = student.StudentID,
ISBN = student.ISBN.Value,
};
db.Loans.Add(l);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ISBN = new SelectList(db.Books, "ISBN", "Titulli", student.ISBN);
return View(student);
}
//
// GET: /Student/Edit/5
public ActionResult Edit(int id = 0)
{
Student student = db.Students.Find(id);
if (student == null)
{
return HttpNotFound();
}
ViewBag.ISBN1 = new SelectList(db.Books, "ISBN", "Titulli");
return View(student);
}
//
// POST: /Student/Edit/5
[HttpPost]
public ActionResult Edit(Student student)
{
if (ModelState.IsValid)
{
db.Entry(student).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ISBN1 = new SelectList(db.Books, "ISBN", "Titulli", student.ISBN);
return View(student);
}
ローンに保存する前にコードを配置した場合も、この場合、「Nullableオブジェクトには値が必要です」というエラーが表示されます。
StudentController.cs II
public ActionResult Create()
{
ViewBag.ISBN = new SelectList(db.Books, "ISBN", "Titulli");
return View();
}
//
// POST: /Student/Create
[HttpPost]
public ActionResult Create(Student student)
{
if (ModelState.IsValid)
{
db.Students.Add(student);
db.SaveChanges();
Loan l = new Loan()
{
StudentID = student.StudentID,
ISBN = student.ISBN.Value,
};
db.Loans.Add(l);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ISBN = new SelectList(db.Books, "ISBN", "Titulli", student.ISBN);
return View(student);
}
//
// GET: /Student/Edit/5
public ActionResult Edit(int id = 0)
{
Student student = db.Students.Find(id);
if (student == null)
{
return HttpNotFound();
}
ViewBag.ISBN1 = new SelectList(db.Books, "ISBN", "Titulli");
return View(student);
}
//
// POST: /Student/Edit/5
[HttpPost]
public ActionResult Edit(Student student)
{
if (ModelState.IsValid)
{
db.Entry(student).State = EntityState.Modified;
db.SaveChanges();
Loan w = new Loan()
{
StudentID = student.StudentID,
ISBN = student.ISBN.Value,
};
db.Loans.Add(w);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ISBN1 = new SelectList(db.Books, "ISBN", "Titulli", student.ISBN);
return View(student);
}