asp.net-mvc 使用 ASP.NET MVC 4 将数据保存/更新到多个表中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18261172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 03:05:39  来源:igfitidea点击:

Save/Update Data into multiple tables using ASP.NET MVC 4

asp.net-mvcentity-frameworkasp.net-mvc-4entity-framework-4

提问by Jaan

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

有人可以帮助我如何使用 ViewModel 将数据保存和更新到多个实体中吗?

I have a ViewModel that looks like this:

我有一个如下所示的 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()
    { }

    }

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.

我能够检索数据(来自多个实体)并将其显示到视图中。但是,现在我被困在如何使用新数据保存和更新上述实体上。大多数示例是 1-1 关系映射是自动的,但在这种情况下数据属于多个实体。

What is the best way to do this? Thanks.

做这个的最好方式是什么?谢谢。

回答by Mardok

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:

正如 Qazi 提到的,你应该有导航属性。然后在客户端,您应该为您的 ID 属性设置隐藏字段以进行编辑:

@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.

您不需要分配 ID 属性,但需要分配导航属性。

回答by Scott

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

回答by Qazi

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

在使用关系数据库时,我的理解是 studentaddress 将是 Student 的孩子,如 StudentAddress 和 StudentPhoto 表中 StudentId 外键的代码所示。如果您将导航属性添加到 Student 并为这些属性分配地址和照片,实体框架将保存它们。就像是

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

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