【问题标题】:Many to Many relationship with ApplicationUser与 ApplicationUser 的多对多关系
【发布时间】:2017-03-30 14:52:54
【问题描述】:

我正在我的 ApplicationUser 类和一个课程类之间建立一个代码优先、多对多的关系。创建模型时,Entity Framework 会构建两个表和相交的数据透视表。但是,这两个表似乎都没有从数据透视表 (LessonApplicationUsers) 中获取数据。两个 List 变量似乎都不包含学生列表或课程列表。我试图结合的两个实体都已存在于数据库中

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}
}

我的数据库上下文

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&lt;Lesson&gt;();
  • smacks head 在我看到这个之前我刚刚尝试过它并且它有效....我是个笨蛋..

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


【解决方案1】:

virtual 标记您的列表以启用延迟加载。也不需要初始化列表Lessons = new List&lt;Lesson&gt;();

【讨论】:

猜你喜欢
  • 2022-01-12
  • 2011-06-02
  • 1970-01-01
  • 2018-03-16
  • 2017-08-25
  • 2015-09-12
  • 2017-06-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多