如何从ASP.NET MVC中的相关表更新表属性

时间:2018-01-20 10:52:15

标签: c# asp.net asp.net-mvc entity-framework

我最近开始使用ASP.NET,我必须说我非常喜欢它。但在每一段关系中,你必须在这里和那里遇到一些障碍。这是我的:

我的首发项目包括创建简单的学校管理系统。我有几张桌子(学生,学生地址,成绩和课程)。

这里有两个表有问题:

1)学生表:

  public Student()
        {

            this.Courses = new HashSet<Course>();
        }

        public int StudentId { get; set; }

        [Required] 
        [StringLength(50, MinimumLength = 2, ErrorMessage = "The name must have over 2 and under 50 characters!")] // stavlja ograničenje na duljinu stringa u bazi
        public string Name { get; set; }

        [Required] 
        [StringLength(50, MinimumLength = 2, ErrorMessage = "The name must have over 2 and under 50 characters!")]
        public string Surname { get; set; }

        public int CurrentGradeId { get; set; }
        public Grade CurrentGrade { get; set; }
        public virtual StudentAdress Address { get; set; }

        public virtual ICollection<Course> Courses { get; set; }

2)学生地址表:

        public int StudentId { get; set; }
        public string Address1 { get; set; }
        public string Adress2 { get; set; }
        public string City { get; set; }
        public int ZipCode { get; set; }
        public string Country { get; set; }

        public virtual Student Student { get; set; }

简而言之,我正在尝试在学生编辑操作方法中更新StudentAddresses属性(更准确地说是Student的Address1属性)。

以下是编辑学生的视图:

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Student</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.StudentId)

    <div class="form-group">
        @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Surname, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Surname, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Surname, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.CurrentGradeId, "CurrentGradeId", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("CurrentGradeId", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.CurrentGradeId, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.Address.Address1, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Address.Address1, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Address.Address1, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Save" class="btn btn-default" />
        </div>
    </div>
</div>

最后这里是StudentsController的编辑操作方法:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "StudentId,Name,Surname,CurrentGradeId")] Student student  )
{

    if (ModelState.IsValid)
    {

        // getting student id for current studentid
        StudentAdress addresa = db.Addresses.Find(student.StudentId);

        // trying to bind input value
        addresa.Address1 = student.Address.Address1.ToString();

        // saving new value in StudentAddresses field Address1
        db.Entry(addresa).State = EntityState.Modified;
        db.SaveChanges();

        db.Entry(student).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    ViewBag.CurrentGradeId = new SelectList(db.Grades, "GradeId", "GradeName", student.CurrentGradeId);
    return View(student);
}

因此,在Edit方法中,我想在Student表的Edit方法中保存Address1的新输入值。或者更简单一点,我想在编辑Student class

时更新StudentAddress类中的字段Address1

更新1

所以,让我们说我已经弄明白了,但我仍然想知道这是否正确和正确。

在学生编辑操作方法中,我添加了addresa.Address1 = Request.Form["Address.Address1"];,其中我使用属性name=Address.Address1更新了字段并且它做了一个技巧,但我想知道它是否正确的方法呢?

请记住,我已尝试过这个

**addresa.Address1 = student.Address.Address1;** 

但使用这种“清洁”方法给了我:

  

System.NullReferenceException:未将对象引用设置为实例   一个对象。

我可以使用其他方法更新Address.Address1字段吗?

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "StudentId,Name,Surname,CurrentGradeId")] Student student  )
        {

            if (ModelState.IsValid)
            {


                StudentAdress addresa = db.Addresses.Find(student.StudentId);

                // newly added line
                addresa.Address1 = Request.Form["Address.Address1"];
                db.Entry(addresa).State = EntityState.Modified;
                db.SaveChanges();

                db.Entry(student).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.CurrentGradeId = new SelectList(db.Grades, "GradeId", "GradeName", student.CurrentGradeId);
            return View(student);
        }

1 个答案:

答案 0 :(得分:0)

你的人际关系错了。

StudentAddress模型中,我们可以看到StudentId外键,这意味着StudentStudentAddress之间的关系是一对多。但是在您的Student模型中,您virtual StudentAdress Address应为ICollection<StudentAdress> Addresses

在您的添加/编辑中,您可以这样做:

var student = context.Student.Find(1);

student.Addresses.Add(new StudentAdress {
    Address1 = "Ul. Janka Leskovara",
    City = "Pregrada",
    ZipCode = 49218,
    Country = "Hrvatska"
});

context.SaveChanges();