我有以下表格:StudentCourses
是Student
和Course
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
EntityTypeConfiguration
是否正确?