ASP.Net MVC Update Multiple Tables http://stackoverflow.com/questions/18261172/save-update-data-into-multiple-tables-using-asp-net-mvc-4
[HttpPost]
public ActionResult Create(StudentViewModel studentViewModel)
{
if (!ModelState.IsValid) // added ! so that you can do something if it is valid other than redisplay the Create View with the model
{
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
};
db.Students.Add(s);
db.SaveChanges(); // Post the changes with the student and save changes so you have the correct studentId PrimaryKey value from the database. Note: EF should update your object with the correct Id on SaveChanges()
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
};
// don't add it again! db.Students.Add(s);
db.StudentAddress.Add(sa);
db.StudentPhoto.Add(sp);
db.SaveChanges();
return RedirectToAction("Home");
}