Razor-Pages - 按日期搜索

Razor-Pages - Searching by a Date

我正在创建一个内部 Razor Pages 应用程序,它使用 Entity Framework 连接到 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();
    }
}

如果搜索字符串是日期,我能够成功解析它,但在位置上出错。错误是:

InvalidOperationException: The LINQ expression 'DbSet .Where(w => w.DateAdded.ToShortDateString() == __ToShortDateString_0)' 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().

当按姓氏搜索时搜索有效。

有什么想法吗?

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

 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 包中。