EF 核心中的计数总和
Sum of count in EF core
我有一个数据库查询如下:
Courses.Where(c => (c.MaxParticipants != 0) && (c.CourseBookings.Sum(c => c.CourseParticipants.Count()) / c.MaxParticipants <= 0.5) && (c.CourseSubs.FirstOrDefault().BookedDates.FirstOrDefault().FromDate - DateTime.Today).Days <= 1)
查询在 ef 6 中有效,但在 ef core 中无效,这是它需要做的。
为了让它发挥作用,我重写了查询。除了 c.CourseBooking.Sum (c => c.CourseParticipant.Count() 之外的所有部分似乎都很好。目前我收到一个异常消息“无法对包含聚合或子查询的表达式执行聚合函数”
from co in DbContext.Course
join cb in DbContext.CourseBooking on co.CourseId equals cb.CourseId
join cs in DbContext.CourseSub on cb.CourseId equals cs.CourseId
join bd in DbContext.BookedDate on cs.CourseSubId equals bd.CourseSubId
where (co.MaxParticipants != 0) && (EF.Functions.DateDiffDay(bd.FromDate, DateTime.Today) <= 1)
select co;
我怎样才能写出计数的总和?
你可以这样做:
from co in DbContext.Course
join cb in DbContext.CourseBooking on co.CourseId equals cb.CourseId
join cs in DbContext.CourseSub on cb.CourseId equals cs.CourseId
join bd in DbContext.BookedDate on cs.CourseSubId equals bd.CourseSubId
where (co.MaxParticipants != 0) && (EF.Functions.DateDiffDay(bd.FromDate, DateTime.Today) <= 1)
group new {cb, cs, bd} by co into groupedInfo
select new
{
Course = groupedInfo.Key,
Booking = groupInfo.Sum(x=>x.cb.CourseParticipants) // if this is a number field
// add any other sum you need here
};
我有一个数据库查询如下:
Courses.Where(c => (c.MaxParticipants != 0) && (c.CourseBookings.Sum(c => c.CourseParticipants.Count()) / c.MaxParticipants <= 0.5) && (c.CourseSubs.FirstOrDefault().BookedDates.FirstOrDefault().FromDate - DateTime.Today).Days <= 1)
查询在 ef 6 中有效,但在 ef core 中无效,这是它需要做的。
为了让它发挥作用,我重写了查询。除了 c.CourseBooking.Sum (c => c.CourseParticipant.Count() 之外的所有部分似乎都很好。目前我收到一个异常消息“无法对包含聚合或子查询的表达式执行聚合函数”
from co in DbContext.Course
join cb in DbContext.CourseBooking on co.CourseId equals cb.CourseId
join cs in DbContext.CourseSub on cb.CourseId equals cs.CourseId
join bd in DbContext.BookedDate on cs.CourseSubId equals bd.CourseSubId
where (co.MaxParticipants != 0) && (EF.Functions.DateDiffDay(bd.FromDate, DateTime.Today) <= 1)
select co;
我怎样才能写出计数的总和?
你可以这样做:
from co in DbContext.Course
join cb in DbContext.CourseBooking on co.CourseId equals cb.CourseId
join cs in DbContext.CourseSub on cb.CourseId equals cs.CourseId
join bd in DbContext.BookedDate on cs.CourseSubId equals bd.CourseSubId
where (co.MaxParticipants != 0) && (EF.Functions.DateDiffDay(bd.FromDate, DateTime.Today) <= 1)
group new {cb, cs, bd} by co into groupedInfo
select new
{
Course = groupedInfo.Key,
Booking = groupInfo.Sum(x=>x.cb.CourseParticipants) // if this is a number field
// add any other sum you need here
};