'Razor-Pages - Searching by a Date

I am creating an in-house Razor Pages application which connects to a SQL database using Entity Framework. I have a page with a search form and I want to be able to search for records based on an entered date.

Here is what I have so far:

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();
    }
}

I am able to successfully parse the searchString if it is a date, but errors out on the where. The error is:

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().

The search works when searching by a Last Name just fine.

Any ideas?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source