我是ASP.NET MVC的新手,我正在尝试制作具有多对多关系(课程/学生)的简单应用程序。用我的语言是(库尔斯/学生)。
这是我的课程
namespace KurseviApp
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
public partial class Kurs
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Kurs()
{
this.Student = new HashSet<Student>();
}
public int PK_Kurs_ID { get; set; }
public string Naziv_Kursa { get; set; }
[NotMapped]
public string Izabrani { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Student> Student { get; set; }
}
}
这是我的学生班
namespace KurseviApp
{
using System;
using System.Collections.Generic;
public partial class Student
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Student()
{
this.Kurs = new HashSet<Kurs>();
}
public int PK_Student_ID { get; set; }
public string Broj_Indeksa { get; set; }
public string Ime { get; set; }
public string Prezime { get; set; }
public string Godina { get; set; }
public string Status { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Kurs> Kurs { get; set; }
}
}
到目前为止,我做得很好。但是,当我创建新课程并选择学生时,就会出现问题。这是我在控制器中的代码
private kurseviEntities db = new kurseviEntities();
public ActionResult Add(int id = 0)
{
Kurs ks = new Kurs();
using (db)
{
ks.Student = db.Student.ToList();
}
return View(ks);
}
[HttpPost]
public ActionResult Add(Kurs kurs)
{
using (db)
{
db.Student.Add(kurs); //THIS LINE IS A PROBLEM
db.SaveChanges();
}
return RedirectToAction("index");
}
这给了我我在文章标题中写的错误。如果我删除该行,则说明课程已成功创建,但是仍然缺少将学生添加到课程中的信息。欢迎大家的帮助,在此先感谢。
编辑:这是我的观点
@model KurseviApp.Kurs
@{
ViewBag.Title = "Add";
}
<h2>Add</h2>
@using (Html.BeginForm())
{
<div class="form-horizontal">
@Html.HiddenFor(model => model.PK_Kurs_ID)
@Html.LabelFor(model => model.Naziv_Kursa, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Naziv_Kursa, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Naziv_Kursa, "", new { @class = "text-danger" })
</div>
<label>Odabir studenata</label>
@Html.DropDownListFor(model => model.Izabrani,
new SelectList(Model.Student, "PK_Student_ID", "Ime"),
new { @class="choosen-select", id = "normalDropDown" })
<input type="submit" name="name" value="submit" />
</div>
}
@section scripts {
<script>
$(function () {
$("#normalDropDown").chosen({ width: "15%" });
});
</script>
}
答案 0 :(得分:0)
Kurs
和Students
是不同类型的事物。 db.Students
是Students
的列表,您正尝试将新的Kurs
直接添加到该列表中。我的猜测是,您想获得一个特定的学生,然后调用student.Kurs.Add(kurs)
将Kurs
添加到特定学生的kurs列表中。