0

Can somebody help me on how to save and update data into multiple entities using a ViewModel?

I have a ViewModel that looks like this:

  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()
    { }

    }

My Controller is:

  [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");
    }

I was able to retrieve and display the data (from multiple entities) into the view. However, now I'm stuck on how can I save and update the above entities with the new data. Most of the examples are 1-1 relationship the mapping is automatic, but in this case the data belongs to multiple entities.

What is the best way to do this? Thanks.

1
  • What's the problem? You only show what you do. Commented Aug 15, 2015 at 9:08

3 Answers 3

2

First of all your models should look like this:

public class Student
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int StudentID { get; set; }

    public string Speciality { get; set; }

    public DateTime DateOfJoinig { get; set; }

    public string Qualification { get; set; }

    public string Email { get; set; }
}

public class StudentAddress
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int StudentAddressID { get; set; }

    [Required]
    [ForeignKey("Student")]
    public int StudentID { get; set; }

    public virtual Student Student { get; set; }

    public string Address { get; set; }

    public string Area { get; set; }

    public string City { get; set; }

    public string State { get; set; }

    public string Pincode { get; set; }

    public string Phone { get; set; }

    public string Mobile { get; set; }
}

public class StudentPhoto
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int StudentPhotoID { get; set; }

    [Required]
    [ForeignKey("Student")]
    public int StudentID { get; set; }

    public virtual Student Student { get; set; }

    public string Photo { get; set; }
}

As Qazi mentioned you should have navigation properties. Then on client side you should have hidden fields for your ID properties for editing purpose:

@Html.HiddenFor(s => s.StudentID)

After that your controller method will look like this:

    [HttpPost]
    public ActionResult Create(StudentViewModel studentViewModel)
    {
        if (!ModelState.IsValid)
        {
            return View(studentViewModel);
        }

        studentViewModel.StudentAddress.Student = studentViewModel.Student;
        studentViewModel.StudentPhoto.Student = studentViewModel.Student;
        if (studentViewModel.Student.StudentID > 0)
            db.Students.Attach(studentViewModel.Student);
        else
            db.Students.Add(studentViewModel.Student);
        db.SaveChanges();
        return RedirectToAction("Home");
    }

You don't need to assign ID properties, but you do need to assign navigation properties.

Sign up to request clarification or add additional context in comments.

Comments

0

not tested but this may help

[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");
}

1 Comment

but i think the db.Save would address the same table in the database
0

While using a relational database, it is my understanding the studentaddress will be child of Student as shown in code by StudentId foreign key in both StudentAddress and StudentPhoto table. If you add navigation properties to Student and assign address and photo to these properties Entity framework will save them. Something like

Student s = new Student {...}
s.StudentAddress = new StudentAddress {...}
s.StudentPhoto = new StudentPhoto {...}

db.Students.Add (s);
db.SaveChanges();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.