Entity Framework 6 - 如何通过单个查询对多对多关系中的项目进行计数?
Entity Framework 6 - How to count items in a many-to-many relationship via a single query?
对于菜鸟 EF 问题表示歉意,但我正在努力使它正常工作,并且肯定已经达到了寻求帮助阶段:)
这里有两个简化的类:
public class Course
{
public int Id { get; set; }
public string Name { get; set; }
public IList<CourseTag> CourseTags { get; set; }
...
}
public class CourseTag
{
public int Id { get; set; }
public string Name { get; set; }
public IList<Course> Courses { get; set; }
...
}
我只是想计算与课程相关的 CourseTag 的数量,在单个查询中。
我可以 SELECT 特定 CourseTagId 的课程(如下所示),SELECTS 课程就好了...
from course in Courses
from tag in course.CourseTags
where tag.Id == 3
select course
但我不知道如何计算与特定相关的课程的数量CourseTag(不使用额外的单独查询)
我尝试了以下几行的变体,但就是想不出正确的语法...
from course in Courses
from tag in course.CourseTags
where tag.Id == 3
**course.Count()??**
我已经想出如何将其分成两个查询来获得结果 - 但似乎没有必要执行两个查询只是为了计算一些东西 - 必须有一种方法可以将其简化为单个查询?
var courseResult = from course in Courses
from tag in course.CourseTags
where tag.Id == 3
select course;
var totalNumber = courseResult.Count();
我敢肯定这一定很简单(如果不使用 EF/Linq 会很容易)但是我的脑子完全被 EF/Linq 卡住了。任何指点将不胜感激,谢谢。
好吧,这似乎是将其简化为单个查询的一种方法。不确定我现在是否真的有所收获,但由于没有其他人有任何建议,希望这可能对其他人有所帮助。
var result = Courses.SelectMany(c => c.CourseTags.Select(t => new { c, t })) //anon obj of course with tag
.Where(c => (c.t.Id == 3)) //filter by TagId == 3
.Select(c => c.c.Id) //limit result to a single field - no need to pull all the data just to count it
.Count();
这会选择课程及其相关(多对多)标签作为匿名对象 - (c, t) 是课程和标签。
SelectMany 将结果数据展平,以便对其进行计数。
对于菜鸟 EF 问题表示歉意,但我正在努力使它正常工作,并且肯定已经达到了寻求帮助阶段:)
这里有两个简化的类:
public class Course
{
public int Id { get; set; }
public string Name { get; set; }
public IList<CourseTag> CourseTags { get; set; }
...
}
public class CourseTag
{
public int Id { get; set; }
public string Name { get; set; }
public IList<Course> Courses { get; set; }
...
}
我只是想计算与课程相关的 CourseTag 的数量,在单个查询中。
我可以 SELECT 特定 CourseTagId 的课程(如下所示),SELECTS 课程就好了...
from course in Courses
from tag in course.CourseTags
where tag.Id == 3
select course
但我不知道如何计算与特定相关的课程的数量CourseTag(不使用额外的单独查询)
我尝试了以下几行的变体,但就是想不出正确的语法...
from course in Courses
from tag in course.CourseTags
where tag.Id == 3
**course.Count()??**
我已经想出如何将其分成两个查询来获得结果 - 但似乎没有必要执行两个查询只是为了计算一些东西 - 必须有一种方法可以将其简化为单个查询?
var courseResult = from course in Courses
from tag in course.CourseTags
where tag.Id == 3
select course;
var totalNumber = courseResult.Count();
我敢肯定这一定很简单(如果不使用 EF/Linq 会很容易)但是我的脑子完全被 EF/Linq 卡住了。任何指点将不胜感激,谢谢。
好吧,这似乎是将其简化为单个查询的一种方法。不确定我现在是否真的有所收获,但由于没有其他人有任何建议,希望这可能对其他人有所帮助。
var result = Courses.SelectMany(c => c.CourseTags.Select(t => new { c, t })) //anon obj of course with tag
.Where(c => (c.t.Id == 3)) //filter by TagId == 3
.Select(c => c.c.Id) //limit result to a single field - no need to pull all the data just to count it
.Count();
这会选择课程及其相关(多对多)标签作为匿名对象 - (c, t) 是课程和标签。
SelectMany 将结果数据展平,以便对其进行计数。