0

I am using .NET Core 5 / Entity Framework Core as a backend for my app.

I have a controller from which I want to return experiments that are set to expire soon.

The logic is, I want the controller to return experiments that are set to expire in 31 days or 7 days.

Visual Studio builds the project with no errors, but when I try to hit the controller, I get this error:

Message=The LINQ expression 'DbSet()
.Where(p => (int)(p.DateOfExpiration - __currentDate_0).TotalDays == 31 || (int)(p.DateOfExpiration - __currentDate_0).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 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'.
Source=Microsoft.EntityFrameworkCore

Here is my controller:

// GET: api/ExpiringExperiments
[HttpGet("ExpiringExperiments")]
public  List<Experiment> ExpiringExperiments()
{
    var currentDate = DateTime.Now;

    var experiments =  _context.Experiment
        .Include(p => p.ExperimentType)
        .Include(p => p.Location)
        .Where(p => ((int)(p.DateOfExpiration - currentDate).TotalDays == 31) || ((int)(p.DateOfExpiration - currentDate).TotalDays == 7))
        .ToList();

    return experiments;
}

I tried following its suggestions to use AsEnumerable, but that throws a new error when trying to build the project:

Cannot implicitly convert Systems.Collections.Generic.IEnumerable to Systems.Collections.Generic.List

I'm not sure what to do here.

Is there something in my query I'm doing wrong?

Thanks!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
SkyeBoniwell
  • 6,345
  • 12
  • 81
  • 185

1 Answers1

1

try this

var currentDate = DateTime.Now;

return  _context.Experiment
        .Include(p => p.ExperimentType)
        .Include(p => p.Location)
        .Where(p => EF.Functions.DateDiffDay(currentDate,p.DateOfExpiration) == 31) 
        || EF.Functions.DateDiffDay(currentDate,p.DateOfExpiration) == 7)
        .ToList();
Serge
  • 40,935
  • 4
  • 18
  • 45