有人能夠首先澄清在EF數據庫中有多少關係可以工作。 例如Student
和Course
表中的關係是多對多的關係。我已經有一個數據庫。MVC EF數據庫首先多對多
所以我已經創建了一個.edmx
的類Student
和Courses
創建汽車。並且我在StudentCourseViewModel.cs
中添加了一個新課程。這個想法是爲了控制與它的關係。 我StudentCourseViewModel
containts如下:
public class StudentCourseViewModel
{
public Student Student{ get; set; }
public IEnumerable<SelectListItem> AllCourses{ get; set; }
private List<int> _selectedCourse;
public List<int> SelectedCourse
{
get
{
if (_selectedCourse == null)
{
_selectedCourse = Student.Courses.Select(m => m.pkID).ToList();
}
return _selectedCourse;
}
set { _selectedCourse = value; }
}
public ActionResult Create()
{
ViewBag.Courses = new SelectList(db.Courses, "pkID", "Name");
return View();
}
public ActionResult Create(StudentCourseViewModel model,[Bind(Include = "pkID,Name")] Student student)
{
if (ModelState.IsValid)
{
if (student == null)
return HttpNotFound();
// Remove items that were unselected
db.Courses.Where(m => !model.SelectedCourses
.Contains(m.pkID))
.ToList()
.ForEach(m => student.Courses.Remove(m));
// Add newly selected items
var existingClientIds = student.Courses.Select(m => m.pkID).ToList();
db.Courses.Where(m => model.SelectedCourses.Except(existingClientIds)
.Contains(m.pkID))
.ToList()
.ForEach(m => student.Courses.Add(m));
db.students.Add(student);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(student);
}
我想現在該怎麼處理// GET:/Create
和// POST:/Create
以及如何查看課程的create.cshtml
名單? 我得到與上面的代碼以下錯誤:
型「System.Data.Entity.Infrastructure.DbUpdateException」的異常出現在EntityFramework.dll但在用戶代碼中沒有處理
更多信息:更新條目時發生錯誤。詳情請參閱內部例外。
關係如何映射到數據庫中,你有一箇中間'StudentCourse'映射表嗎?目前尚不清楚您的「ViewModel」如何以任何方式映射關係。 –
嘿ja我在數據庫中有一箇中間的StudentCourse表,但是當我創建.edmx時,StudentCourse表沒有顯示在模型中,而是用「*」符號表示多對多的鏈接。 –
它聽起來好像已經被正確映射了,你沒有爲你的中間表生成一個類,並且只填充相關的導航屬性。你的控制器/視圖中有什麼是你遇到問題? –