【发布时间】:2019-10-11 19:22:57
【问题描述】:
我有一个查询方法,它应该给我从今天到 7 天的下一场比赛,给定一个联赛 ID。所以如果今天的日期是 2019 年 10 月 11 日,那么它应该给我所有的体育比赛,直到 2019 年 10 月 18 日。
public IQueryable<MatchDTO> GetMatchesForNextSevenDaysByLeagueAsync(int leagueId)
{
var todayDate = DateTime.Now;
var matches = _context.Matches.Include(e => e.HomeTeam).Include(e => e.AwayTeam).Include(e => e.League).Where(m => m.LeagueId == leagueId).OrderBy(m => m.MatchDate).ThenBy(m => m.Time).Where(m => ((todayDate - m.MatchDate).Days) <=7).Select(m => DTOConverter.ConvertMatchToDTO(m));
return matches;
}
调用抛出异常:
"The LINQ expression 'Where<Match>(\r\n source:
ThenBy<Match, DateTime>(\r\n source: OrderBy<Match, DateTime>(\r\n
source: Where<Match>(\r\n source: DbSet<Match>, \r\n
predicate: (m) => m.LeagueId == (Unhandled parameter: __leagueId_0)), \r\n
keySelector: (m) => m.MatchDate), \r\n keySelector: (m) => m.Time), \r\n
predicate: (m) => m.MatchDate - (Unhandled parameter: __todayDate_1).TotalDays <= 7)'
could not be translated. Either rewrite the query in a form that can be translated, or
switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(),
ToList(), or ToListAsync().
See https://go.microsoft.com/fwlink/?linkid=2101038 for more information."
对我来说,它看起来不像我比较 .Where(m => ((todayDate - m.MatchDate).Days) <=7) 中日期的方式
我曾尝试使用客户端评估,但速度太慢。关于如何重写此代码以使代码正常工作的任何想法。
请注意,我使用的是 EF Core 3.0
【问题讨论】:
-
使用
.Where(m => m.MatchDate < calculatedDayWith7DaysOffset)(或>)之类的东西怎么样?与常数值进行简单比较即可。 -
不确定您所说的计算的DayWith7DaysOffset 是什么意思。我应该将它与今天的日期进行比较。你的意思是取今天的日期并给它一个 + 7 天的偏移量吗?
标签: c# .net-core ef-core-3.0