asp.net mvc在linq到sql中的多对多关系

时间:2013-09-19 13:11:30

标签: c# asp.net asp.net-mvc linq asp.net-mvc-4

我有一个asp.net mvc项目,其中包含搜索过滤器表单。还有2个表多对多关系,例如学生和学生。大学。在我的表格中显示大学的下拉列表。然后从形式到行动的视图飞大学的ID,我需要整理我的学生表,只有这所大学的学生。我还有另一个用于过滤的下拉菜单,但是他们的ID存在于Student表中而不是UniversityId中,而不包括在Students表中。而且我不知道我该怎么做以及该做什么。此时我的查询看起来像下一个:

var model = repository.GetStudents()
.Where(x => x.DropId == (DropId?? x.DropId) && 
x.DropId1 == (DropId1 ?? x.DropId1) && 
//somewhere here must be expression for UniversityId
).ToList();

有人有什么想法吗?

修改

public class Student {
public int StudentId { get; set; }
public int DropId { get; set; }
public Drop Drop { get; set; }
public int DropId1 { get; set; }
public Drop1 Drop1 { get; set; }
public ICollection<University> Universities { get; set; }
}

public class University {
public int UniversityId { get; set; }
public string UniversityNameShort { get; set; }
public ICollection<Student> Students { get; set; }
}

1 个答案:

答案 0 :(得分:3)

一旦你获得了所选大学的Id值,让我们在一个名为universityId的变量中说,你可以通过这个查询得到大学的学生:

repository.GetStudents()
          .Where(x => x.DropId == (DropId?? x.DropId) 
                   && x.DropId1 == (DropId1 ?? x.DropId1)
                   && x.Universities.Any(u => u.UniversityId == universityId)
).ToList();