Razor-Pages - 按日期搜索

理查德·阿姆斯特朗

我正在创建一个内部 Razor Pages 应用程序,它使用实体框架连接到 SQL 数据库。我有一个带有搜索表单的页面,我希望能够根据输入的日期搜索记录。

这是我到目前为止所拥有的:

public async Task OnGetAsync(string searchString)
{
    // provide an IQueryable list of web registrants that can be parsed.
    // IQueryable<Models.WebPestMSTR> webRegistrationIQ = (from a in _context.WebPestMSTR
    //                                                     select a);

    // If the Search string is empty than only show the unprocessed web registration.  Otherwise parse the table for matching records.
    if (!String.IsNullOrEmpty(searchString))
    {
        // There is a search parameter. Parse the query for matching records.
        // Parse the search parameter to see if it is a date (bool isCertNo = BigInteger.TryParse(searchString, out numOut);)
        if (DateTime.TryParse(searchString, out DateTime dateTime))
        {
            WebPestMSTR = await _context.WebPestMSTR
                    .Where(a => a.DateAdded.ToShortDateString() == dateTime.ToShortDateString())
                    .Include(w => w.Course)
                    .Include(w => w.MiraInfo)
                    .ToListAsync();

            // webRegistrationIQ = webRegistrationIQ.Where(a => a.DateAdded.ToShortDateString() == dateTime.ToShortDateString());
        }
        else
        {
            IQueryable<Models.WebPestMSTR> webRegistrationIQ = (from a in _context.WebPestMSTR
                                                                select a);

            webRegistrationIQ = webRegistrationIQ.Where(a => a.LastName.Contains(searchString));

            WebPestMSTR = await webRegistrationIQ
                    .Include(w => w.Course)
                    .Include(w => w.MiraInfo)
                    .ToListAsync();
        }
    }
    else
    {
        // No search parameters so only show unprocessed records.
        WebPestMSTR = await _context.WebPestMSTR
            .Include(w => w.Course)
            .Include(w => w.MiraInfo)
            .Where(w => w.IsProcessed == false)
            .ToListAsync();
    }
}

如果它是日期,我能够成功解析 searchString,但在何处出错。错误是:

InvalidOperationException:无法翻译 LINQ 表达式“DbSet .Where(w => w.DateAdded.ToShortDateString() == __ToShortDateString_0)”。以可翻译的形式重写查询,或通过插入对 AsEnumerable()、AsAsyncEnumerable()、ToList() 或 ToListAsync() 的调用显式切换到客户端评估。

当按姓氏搜索时,搜索工作正常。

有什么想法吗?

塞尔吉

如果您只需要比较日期(没有时间)并且您使用的是 ms sql server,您可以尝试

 WebPestMSTR = await _context.WebPestMSTR
           .Where(a => EF.Functions.DateDiffDay(a.DateAdded, dateTime)==0)
           .Include(w => w.Course)
            .Include(w => w.MiraInfo)
            .ToListAsync();

如果您需要更多的大小比较,您可以使用 EF.Functions.DateDiffMinute 或 EF.Functions.DateDiffSecond 代替。此函数包含在 Microsoft.EntityFrameworkCore.SqlServer nuget 包中。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章