有人可以帮助我如何使用 ViewModel 将数据保存和更新到多个实体中吗?
我有一个看起来像这样的 ViewModel:
public class StudentViewModel
{
public Student student;
public StudentAddress studentAddress { get; set; }
public StudentPhoto studentPhoto { get; set; }
// Three entities are related to one to one relationship
public StudentViewModel()
{ }
}
我的控制器是:
[HttpPost]
public ActionResult Create(StudentViewModel studentViewModel)
{
if (ModelState.IsValid)
{
return View(studentViewModel);
}
Student s = new Student()
{
Name =studentViewModel.Student.Name,
Speciality = studentViewModel.Student.Speciality,
DateOfReg = studentViewModel.Student.DateOfJoinig,
Qualification = studentViewModel.Student.Qualification,
Email = studentViewModel.Student.Email
};
StudentAddress sa = new StudentAddress()
{
StudentId= studentViewModel.Student.StudentId,
Address = studentViewModel.StudentAddress.Address,
Area = studentViewModell.StudentAddress.Area,
City = studentViewModel.StudentAddress.City,
State = studentViewModel.StudentAddress.State,
Mobile = studentViewModel.StudentAddress.Mobile
};
StudentPhoto sp = new StudentPhoto()
{
StudentId= studentViewModel.Student.StudentId,
Photo = studentViewModel.StudentPhoto.Photo
};
db.Students.Add(s);
db.StudentAddress.Add(sa);
db.StudentPhoto.Add(sp);
db.SaveChanges();
return RedirectToAction("Home");
}
视图是:
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Doctor</legend>
@Html.EditorFor(model => model.Student.Name )
@Html.EditorFor(model => model.Student.Speciality)
@Html.EditorFor(model => model.Student.DateOfJoinig)
@Html.EditorFor(model => model.Student.Standard)
@Html.HiddenFor(model => model.Student.StudentId)
@Html.EditorFor(model => model.StudentAddress.Address)
@Html.EditorFor(model => model.StudentAddress.Area)
@Html.EditorFor(model => model.StudentAddress.City)
@Html.EditorFor(model => model.StudentAddress.State)
@Html.HiddenFor(model => model.Student.StudentId)
@Html.EditorFor(model => model.StudentPhoto.Photo)
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
我能够检索数据(来自多个实体)并将其显示到视图中。但是,现在我被困在如何使用新数据保存和更新上述实体。大多数示例是 1-1 关系映射是自动的,但在这种情况下,数据属于多个实体。
我的问题是当我尝试保存重定向到创建页面的数据时。“ModelState.IsValid”始终为假,因此不保存数据。请帮助我如何进行。
谢谢。