谁能指出我哪里错了!!
我创建了两个简单的类,具有多对多的关系。工作正常,所有表都已正确填充。除了当我尝试检索任何学生课程时,什么都没有返回......
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);
}
}
如果您使用延迟加载,则需要将属性定义为 virtual ,
public virtual ICollection<Course> Courses { get; set; }
如果你愿意,你可以使用预加载,
var students = db.Students.Include(s=>s.Courses).ToList();
http://codetuner.blogspot.com/2011/07/entity-framework-differed-loading-lazy.html http://codetuner.blogspot.com/2011/07/entity-framework-differed-loading-lazy.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)