实体框架

时间:2016-10-23 08:33:50

标签: c# entity-framework-6 ef-fluent-api

我有以下表格:StudentCoursesStudentCourse

的映射表
  • Student(Id,..)
  • Course(Id,..)
  • StudentCourses(StudentId,CourseId)

模型类:

public class Student {
      ....
      ....
      public virtual ICollection<Course> Courses { get; set; } 

}

public class Course {
      ...
      ...
      public virtual ICollection<Student> Students { get; set; } 
}

public class StudentCourse  {
      ...
      ...
      public virtual Student Student { get; set; } 
}

映射设置如下:

public class StudentConfiguration
      : EntityTypeConfiguration<Student>
{
      public StudentConfiguration()
      {
         HasKey(x => x.Id);

         //Many to many
         HasMany(s => s.Course)
            .WithMany(t => t.Students)
            .Map(x =>
            {
               x.ToTable("StudentCourses");
               x.MapLeftKey("StudentId");
               x.MapRightKey("CourseId");
            }
            );
        }
}

public class StudentCourseConfiguration
      : EntityTypeConfiguration<StudentCourse>
{
      public StudentCourseConfiguration()
      {
         HasKey(x => new {x.StudentId, x.CourseId});
      }
}

我正在努力获得Courses的集合,其中包含为每门课程注册的学生人数。

public ActionResult GetAllCourseInfo()
{
         var courses = _context.Course.ToList();
         var courseInfo = new List<CourseInfo>();

         foreach (var course in courses )
         {
            var studentCount = _context.StudentCourse.Count(x => x.Student.CourseName.Equals(course.CourseName));
            courseInfo.Add(new CourseInfo{ CourseName = course.CourseName, Count = studentCount });
         }

         return Json(courseInfo, JsonRequestBehavior.AllowGet);
}

我收到了异常

  

无效的对象名称dbo.StudentCourses1

  1. 如何解决此问题?
  2. 我的EntityTypeConfiguration是否正确?

0 个答案:

没有答案