我有课程Student
和Class
。
public class Student : ApplicationUser
{
public DateTime DateBorn { get; set; }
public virtual ICollection<Class> Classes { get; set; }
}
public class Class
{
public int Id { get; set; }
public int CourseId { get; set; }
public Course Course { get; set; }
public string ProfessorId { get; set; }
public Professor Professor { get; set; }
public short Size { get; set; }
public int Year { get; set; }
public Term Term { get; set; }
public bool Enrollable { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
我正在尝试获取Classes
注册的Student
。我想过在方法class.Students.Contains()
中使用方法.Where()
,但它给我一个例外。
// GET: Classes/Calendar
public async Task<ActionResult> Calendar(int? year, Term? term)
{
year = year ?? DateTime.Now.Year;
term = term ?? (Term)(DateTime.Now.Month / 4);
var student = await UserManager.FindByIdAsync(User.Identity.GetUserId());
var classes = db.Classes
.Where(c => c.Students.Contains(student) && c.Year == year && c.Term == term);
return View(await classes.ToListAsync());
}
例外:Unable to create a constant value of type 'Demosthenes.Core.Models.Student'. Only primitive types or enumeration types are supported in this context.
如何在不必编写显式连接的情况下正确执行此操作?
答案 0 :(得分:1)
如果Student
的主键属性为Id
且User.Identity.GetUserId()
返回类型与Student::Id
相同,则可以尝试此操作。
var id = User.Identity.GetUserId();
var classes = db.Classes
.Where(c => c.Students.Any(s => s.Id == id)
&& c.Year == year && c.Term == term);
答案 1 :(得分:1)
您需要退后一步并更改表格结构。
对于多对多关系,您需要在中间添加联结表,例如
Student
StudentClass
Class
您的代码将成为
var classes = db.Classes
.Where(c => c.StudentClasses
.Any(x=>x.StudentId == student.Id)
&& c.Year == year && c.Term == term);