与ApplicationUser的多对多关系

时间:2017-03-30 14:52:54

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

我正在构建ApplicationUser类和Lesson类之间的Code-First,Many-To-Many关系。创建模型时,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}
}

我的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");

当我尝试运行它时,当我按下我的书按钮时,它会运行代码并执行。检查数据库确实已将键值插入数据透视表。当我加载课程模型以查看其详细信息时,学生属性的计数为0.我已经在这几天了,我感觉我错过了一些简单的东西....但是我已经过了十几次,看不出我做错了什么......

1 个答案:

答案 0 :(得分:1)

使用group by标记您的列表以启用延迟加载。也不需要初始化列表select id, count(*) as count_of_apples from transactions where type = 'apple' group by id order by count(*) desc