有人可以帮助我如何使用 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 DoctorDetailsViewModel()
{ }
}
我的控制器是:
[HttpPost]
public ActionResult Create(StudentViewModel studentViewModel)
{
if (ModelState.IsValid)
{
return View(studentViewModel);
}
Student s = new Student()
{
Name =studentViewModel.Student.Name,
Speciality = studentViewModel.Student.Speciality,
DateOfJoinig = 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,
Pincode = studentViewModel.StudentAddress.Pincode,
Phone = studentViewModel.StudentAddress.Phone,
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");
}
我能够检索数据(来自多个实体)并将其显示到视图中。但是,现在我被困在如何使用新数据保存和更新上述实体。大多数示例是 1-1 关系映射是自动的,但在这种情况下,数据属于多个实体。
做这个的最好方式是什么?谢谢。