更新db时处理一对多关系

时间:2015-08-21 16:30:57

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

如何处理一对多的关系。

型号:

public partial class Student
{
    public student()
    {
        this.Courses = new HashSet<Course>();
    }

    public int pkID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Course> Courses { get; set; }
}

public partial class Course
{
    public int pkID { get; set; }
    public Nullable<int> fkStudentID { get; set; }
    public string Name { get; set; }

    public virtual Student Student  { get; set; }
}

控制器:

public ActionResult Create([Bind(Include = "pkID,Name")] Student student)
{
    student.Courses.Add(course); // How to fetch course from the Student/Create.cshtml and convert it to type Course
    db.Students.Add(student);
    db.SaveChanges();
    return RedirectToAction("Index");
}

查看:

// Student/Create.cshtml
@model School.Student
@{
    ViewBag.Title = "Create";
}
<div>
    @Html.ActionLink("Tillbaka till lista", "Index")
</div>


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
         @Html.LabelFor(model => model.Name, "Namn", htmlAttributes: new { @class = "control-label col-md-2" })
         <div class="col-md-10">
             @Html.DropDownList("Name", null, htmlAttributes: new { @class = "form-control" })
             @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
         </div>
     </div>
    <div class="form-group">
         @Html.LabelFor(model => model.Courses, "Kurs", htmlAttributes: new { @class = "control-label col-md-2" })
         <div class="col-md-10">
             @Html.DropDownList("Courses", null, htmlAttributes: new { @class = "form-control" })
             @Html.ValidationMessageFor(model => model.Courses, "", new { @class = "text-danger" })
         </div>
     </div>
}

问题是如何从.cshtml获取课程数据并更新数据库。 在create函数中我只获取了Name,我知道可以使用Request [&#34; Courses&#34;],但是如何将它存储在课程表中?

谢谢!

3 个答案:

答案 0 :(得分:1)

对于单个课程选择,您在Student课程中添加一列作为 08-22 15:16:34.657: E/AndroidRuntime(27596): java.lang.NullPointerException: Attempt to invoke virtual method 'float android.view.MotionEvent.getX()' on a null object reference 08-22 15:16:34.657: E/AndroidRuntime(27596): at android.view.View.onTouchEvent(View.java:9321) 08-22 15:16:34.657: E/AndroidRuntime(27596): at android.support.design.widget.CoordinatorLayout.onTouchEvent(CoordinatorLayout.java:449) 08-22 15:16:34.657: E/AndroidRuntime(27596): at android.view.View.dispatchTouchEvent(View.java:8388) 08-22 15:16:34.657: E/AndroidRuntime(27596): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2398) 08-22 15:16:34.657: E/AndroidRuntime(27596): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2158) 08-22 15:16:34.657: E/AndroidRuntime(27596): at android.support.v4.widget.DrawerLayout.cancelChildViewTouch(DrawerLayout.java:1491) 08-22 15:16:34.657: E/AndroidRuntime(27596): at android.support.v4.widget.DrawerLayout$ViewDragCallback.peekDrawer(DrawerLayout.java:1739) 08-22 15:16:34.657: E/AndroidRuntime(27596): at android.support.v4.widget.DrawerLayout$ViewDragCallback.access$000(DrawerLayout.java:1624) 08-22 15:16:34.657: E/AndroidRuntime(27596): at android.support.v4.widget.DrawerLayout$ViewDragCallback$1.run(DrawerLayout.java:1630) 08-22 15:16:34.657: E/AndroidRuntime(27596): at android.os.Handler.handleCallback(Handler.java:739) 08-22 15:16:34.657: E/AndroidRuntime(27596): at android.os.Handler.dispatchMessage(Handler.java:95) 08-22 15:16:34.657: E/AndroidRuntime(27596): at android.os.Looper.loop(Looper.java:135) 08-22 15:16:34.657: E/AndroidRuntime(27596): at android.app.ActivityThread.main(ActivityThread.java:5221) 08-22 15:16:34.657: E/AndroidRuntime(27596): at java.lang.reflect.Method.invoke(Native Method) 08-22 15:16:34.657: E/AndroidRuntime(27596): at java.lang.reflect.Method.invoke(Method.java:372) 08-22 15:16:34.657: E/AndroidRuntime(27596): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898) 08-22 15:16:34.657: E/AndroidRuntime(27596): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693) 08-22 15:16:35.965: I/Process(27596): Sending signal. PID: 27596 SIG: 9 并且在视图中你喜欢

public int CourseId{get;set;}

现在,当您选择课程后提交表单时,您将在@Html.DropDownListFor(m => m.CourseId, new SelectList(Model.Courses, "pkID", "Name"), new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.CourseId, "", new { @class = "form-control" }) 创建为ActionResult时获得所选的课程。

如果您需要更多帮助,请告诉我

答案 1 :(得分:0)

嗯......如上所述,问题本身有点不清楚,但我会试一试。 在关系数据库中,许多关系知道一个实体,而不是相反。这意味着one-relation的主键是多关系中的外键。

也就是说,在EF中,当你在一个类(或表)中创建一个容器时,该容器是多关系的,它将具有一个关系的主键,你可以用它来找到特定的多个关系。 / p>

如果这不能回答您的问题,我建议您查看本教程:http://www.entityframeworktutorial.net/code-first/configure-one-to-many-relationship-in-code-first.aspx

答案 2 :(得分:0)

对于多重选择,无需在Student类中添加新列作为CourceId,您可以执行以下操作

var i=0, html="";
$("#CourseId option:selected").each(function () {          
    var courseId = $(this).val();
    html += '<input type="hidden" name="Courses[' + i + '].pkID" id="Courses_' + i + '" value="' + courseId + '"/>';
                i = i + 1;
 });

$("#divDummy").html(html);

这里假设CourseId是你的Dropdown和divDummy的ID,你在表单中取一个空div。 现在,一旦提交,您将获得所选课程ID的列表作为学生。在提交表单之前,应该调用课程及以上的javascript。

如果您需要帮助,请告诉我。