Entity Framework select 从一到多的不同值 table 带过滤器
Entity Framework select distinct values from one to many table with filter
我正在尝试在 EF 中编写查询。
考虑这种关系:
目标是让教师拥有在特定过滤时间段(从-到)之间活跃的全部学生。
我写了以下查询:
var filtered = _context.Teachers
.Join(_context.Students, // Target
fk => fk.Id, // FK
pk => pk.teacherId, // PK
(fk, pk) => new { teach = fk, students = pk }
)
.Where(i => i.students.date_active >= from &&
i.students.date_active <= to)
.OrderBy(i => i.teach.name)
.Select(i => i.teach)
.Include(i => i.Students)
.AsNoTracking();
通过这个查询,我得到了重复的教师。所以我只添加 Distinct()
运算符,我有老师。但是后来我的老师对象仍然包含所有学生。我只想要那个时期的学生。对如何获得好的结果有什么帮助吗?
List<Dto.Teacher> list = filtered.Select(i => Dto.Teacher
{
id = i.Id,
name = i.name
Students = i.Students.Select(j => new Dto.Student
{
id = i.id,
date_active = i.date_active,
}).ToList(),
}).ToList();
public class Teacher()
{
public int id { get; set; }
public string name { get; set; }
public List<Dto.Student> Students { get; set; }
}
在使用 EF 等 ORM 时,应尽可能避免使用 join
运算符。
在您的情况下,您可以尝试以下操作(可能有变化):
_context.Teachers.
Where(t => t.Sudents.Any(s => s.date_active >= from &&
s.date_active <= to)
).
Select(t => new {
teacher = t,
activeStudents = t.Students.Where(s => s.date_active >= from &&
s.date_active <= to)
});
我正在尝试在 EF 中编写查询。
考虑这种关系:
目标是让教师拥有在特定过滤时间段(从-到)之间活跃的全部学生。
我写了以下查询:
var filtered = _context.Teachers
.Join(_context.Students, // Target
fk => fk.Id, // FK
pk => pk.teacherId, // PK
(fk, pk) => new { teach = fk, students = pk }
)
.Where(i => i.students.date_active >= from &&
i.students.date_active <= to)
.OrderBy(i => i.teach.name)
.Select(i => i.teach)
.Include(i => i.Students)
.AsNoTracking();
通过这个查询,我得到了重复的教师。所以我只添加 Distinct()
运算符,我有老师。但是后来我的老师对象仍然包含所有学生。我只想要那个时期的学生。对如何获得好的结果有什么帮助吗?
List<Dto.Teacher> list = filtered.Select(i => Dto.Teacher
{
id = i.Id,
name = i.name
Students = i.Students.Select(j => new Dto.Student
{
id = i.id,
date_active = i.date_active,
}).ToList(),
}).ToList();
public class Teacher()
{
public int id { get; set; }
public string name { get; set; }
public List<Dto.Student> Students { get; set; }
}
在使用 EF 等 ORM 时,应尽可能避免使用 join
运算符。
在您的情况下,您可以尝试以下操作(可能有变化):
_context.Teachers.
Where(t => t.Sudents.Any(s => s.date_active >= from &&
s.date_active <= to)
).
Select(t => new {
teacher = t,
activeStudents = t.Students.Where(s => s.date_active >= from &&
s.date_active <= to)
});