我正在使用Entity Framework开发Web Api应用程序,其中有两个模型和DbContext类:
public class Course
{
[Key]
public int CourseId { get; set; }
[Required]
public string CourseName{ get; set; }
public ICollection<Students> Students { get; set; }
}
public class Students
{
[Key]
public int StudentId { get; set; }
[Required]
public string StudentName{ get; set; }
[Required]
public int StudentAge{ get; set; }
}
//My CourseContext
public class CourseContext : DbContext
{
public CourseContext () : base("CourseDB") { }
public DbSet<Course> Courses { get; set; }
public DbSet<Students> Students { get; set; }
}
我正在使用上面的这些模型对WebAPi进行建模,我需要列出所有正在学习课程的学生,这意味着这些课程将添加到“课程类”的“ ICollection Students”属性中。我曾尝试为此开发解决方案,但由于在模型之间没有外键属性,因此我不知道该怎么做。
...
using (var course_db = new CourseContext ()){
/*but this return all students and repeated ones since one student
can be in more than one course*/
var students= course_db.Course.Include("Students").Select(x=> x.Students);
if (students== null){
return Json(new { success = false });
}
return Json(students, JsonRequestBehavior.AllowGet);
}
...
我已经尝试了下面的代码,但是没有用。我只想检索已注册课程的学生,因为其中一些不是。有人可以帮我吗?
答案 0 :(得分:0)
您需要在模型中进一步建立关系。学生与课程的关系应该是多对多的关系,您在每个关系中都缺少适当的属性,但是缺少联接表和适当的模型构建器(上下文)配置。
重写您的dbcontext模型创建方法以添加您的流利配置:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Build many-to-many relationships
modelBuilder.Entity<Student>()
.HasMany<Course>(c => c.Courses)
.WithMany(s => s.Student)
.Map(pe =>
{
pe.MapLeftKey("Student_ID");
pe.MapRightKey("Course_ID");
pe.ToTable("StudentCoursesTable");
});
}
从您的学生班级中添加缺少的课程:
public class Students
{
public ICollection<Courses> Courses { get; set; }
}