如何在不引发错误的情况下将我的 API 控制器更改为 return 结果?

How can I change my API controller to return results without throwing an error?

我正在使用 .NET Core 5 / Entity Framework Core 作为我的应用程序的后端。

我有一个控制器,我想从中进行 return 即将到期的实验。

逻辑是,我希望控制器 return 实验设置为 31 天或 7 天后到期。

Visual Studio 构建项目没有错误,但是当我尝试点击控制器时,出现此错误:

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

这是我的控制器:

// 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;
}

我尝试按照它的建议使用 AsEnumerable,但是在尝试构建项目时会抛出一个新错误:

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

我不知道该做什么。

我的查询中有什么地方做错了吗?

谢谢!

试试这个

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