C# 操作员'==';无法应用于类型为';int';和';任务<;int>';

C# 操作员'==';无法应用于类型为';int';和';任务<;int>';,c#,async-await,asp.net-core-3.1,C#,Async Await,Asp.net Core 3.1,在ASP.NET Core 3.1中,我试图使我的方法异步化 这是我的密码: public async Task<int> GetMaxNews() { return await _context.PNewses.MaxAsync(s => s.Id); } 公共异步任务GetMaxNews() { 返回wait_context.pnewes.maxancy(s=>s.Id); } 我在这个代码片段中使用了这个方法: public async Task<Lis

在ASP.NET Core 3.1中,我试图使我的方法异步化

这是我的密码:

public async Task<int> GetMaxNews()
{
    return await _context.PNewses.MaxAsync(s => s.Id);
}
公共异步任务GetMaxNews() { 返回wait_context.pnewes.maxancy(s=>s.Id); } 我在这个代码片段中使用了这个方法:

public async Task<List<PNews>> LastNews()
{
    return await _context.PNewses.Where(s => s.Id == GetMaxNews()).ToList();
}
public异步任务LastNews()
{
return wait_context.pnewes.Where(s=>s.Id==GetMaxNews()).ToList();
}
我得到这个错误:

运算符“==”不能应用于“int”和“Task”类型的操作数


有人能帮我吗?问题出在哪里?

当您调用
GetMaxNews()
时,它返回一个
任务。当你等待任务时,你会得到一个int。你想要看起来像

... Where(s => s.Id == await GetMaxNews()) ...

你不能在EF中调用其他函数,首先获取“GetMaxNews”的结果,然后使用它。如下示例代码所示:

public async Task<int> GetMaxNews()
{
    return await _context.PNewses.MaxAsync(s => s.Id);
}


public async Task<List<PNews>> LastNews()
{
    int ResultOfGetMaxNews = await GetMaxNews();
    return await _context.PNewses.Where(s => s.Id == ResultOfGetMaxNews ).ToListAsync();
}

公共异步任务GetMaxNews() { 返回wait_context.pnewes.maxancy(s=>s.Id); } 公共异步任务LastNews() { int ResultOfGetMaxNews=等待GetMaxNews(); return wait_context.pnewes.Where(s=>s.Id==ResultOfGetMaxNews.toListSync(); }
public async Task LastNews(){return await\u context.pnews.Where(s=>s.Id==await GetMaxNews()).ToList()}它不起作用了。这并没有什么意义,您实际上是在尝试返回一个具有最大Id的结果列表。Id通常是聚集的唯一标识列。在大多数情况下,只有一个。在这种情况下,您只需降序
OrderByDescending
然后
first或default
。如果出于某种奇怪的原因,你真的需要它,那么最好做两次往返,得到最大值,然后
where
,因为错误提示:
GetMaxNews()
返回一个
任务,你必须
等待
以某种方式得到它的
int
。。。