[英].Net MVC 5 querying models that have a many-to-many-relationship with ApplicationUser
[英]Many to Many relationship with ApplicationUser
我在ApplicationUser類和Lesson類之間建立了代碼優先,多對多關系。 創建模型后,實體框架將構建兩個表和相交的數據透視表。 但是,兩個表似乎都不從數據透視表(LessonApplicationUsers)接收數據。 兩個列表變量似乎都沒有包含“學生”列表或“課程”列表。 我要結婚的兩個實體已經存在於數據庫中
ApplicationUser類
public class ApplicationUser : IdentityUser
{
public string Address { get; set; }
public int? Age { get; set; }
public ClassLevel? ClassLevel { get; set; }
public string FirstName { get; set; }
public int? Height { get; set; }
public string LastName { get; set; }
public string MobileNumber { get; set; }
public string Postcode { get; set; }
public string Town { get; set; }
public int? Weight { get; set; }
public ApplicationUser()
{
Lessons = new List<Lesson>();
}
public ICollection<Lesson> Lessons { get; set; }
}
課程課
public class Lesson
{
[Key]
public int LessonID { get; set; }
public LessonType ClassType { get; set; }
public ClassLevel? ClassLevel { get; set; }
public DateTime ClassStartDate { get; set; }
public DateTime ClassEndDate { get; set; }
public float ClassCost { get; set; }
public int? InstructorID { get; set; }
public Lesson()
{
Students = new List<ApplicationUser>();
}
public ICollection<ApplicationUser> Students { get; set; }
public enum LessonType {Group,Private}
}
我的DBContext
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<Lesson> Lessons { get; set; }
public DbSet<ApplyViewModel> Applications { get; set; }
最后,我用來添加數據透視表數據的代碼。 當用戶按下預訂表格上的按鈕時,將激活此功能。
public ActionResult BookUser()
{
//Gather required variables
ApplicationUser user = db.Users.First(i => i.UserName == User.Identity.Name);
int classID = int.Parse(Request.Form["classID"]);
using (db)
{
var editedLesson = db.Lessons.Single(s => s.LessonID == classID);
db.Lessons.Attach(editedLesson);
var editedUser = db.Users.Single(s => s.Id == user.Id);
db.Users.Attach(editedUser);
editedLesson.Students.Add(editedUser);
db.SaveChanges();
}
return View("Index");
當我嘗試運行它時,當我按我的書本按鈕時,它將遍歷代碼並執行。 檢查數據庫,它確實已將鍵值插入到數據透視表中。 當我加載課程模型以查看其詳細信息時,Student屬性的計數為0。我已經參加了好幾天,並且感覺到我缺少一些簡單的踢球方法。...但是我已經走了十幾遍,看不到我在做什么錯...
用virtual
標記您的列表以啟用延遲加載。 也不需要初始化列表Lessons = new List<Lesson>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.