有人能指出我哪里错了吗!!
我创建了两个简单的类,它们之间存在多对多的关系。一切正常,所有的表都被正确地填充了。但是当我尝试检索任何学生的课程时,没有返回任何内容...
public partial class Student
{
public Student()
{
Courses = new HashSet<Course>();
}
public int StudentID { get; set; }
[StringLength(50)]
[Required]
public string FirstName { get; set;}
[StringLength(50)]
[Required]
public string LastName {get; set;}
public DateTime? Enroled {get;set;}
public ICollection<Course> Courses { get; set; }
}
public class Course
{
public Course()
{
Students = new HashSet<Student>();
}
public int CourseID { get; set; }
[StringLength(30)]
[Required]
public string CourseTitle { get; set; }
[StringLength(255)]
public string CourseDesc { get; set; }
public ICollection<Student> Students { get; set; }
}
public ContextDB()
: base (@"Data Source=.\SQLEXPRESS;Initial Catalog=CollegeDB;Integrated Security=True")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Course>().HasMany(c=>c.Students).WithMany(p => p.Courses)
.Map(
m=> {
m.MapLeftKey("Course_CourseID");
m.MapRightKey("Student_StudentID");
m.ToTable("CourseStudents");
});
}
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
}
var students = db.Students.ToList();
foreach (Student s in students)
{
Console.WriteLine("{0} {1}", s.FirstName, s.LastName);
foreach (Course c in s.Courses.ToList())
{
Console.WriteLine("{0}", c.CourseTitle);
}
}