【发布时间】:2021-08-16 17:43:19
【问题描述】:
我尝试在我的 lambda 函数中使用 await 来异步完成操作,以简化我遗漏了不必要的操作(where 子句等)的问题,并将异步方法命名为 Services.CustomerAmountService.QueryDbAndReturnResult
该函数接受一个 double(数量之和)并执行许多任务,但最重要的是一个异步调用(firstAsync,这使得函数可等待)
[HttpGet]
public async Task<IActionResult> GetCustomersAndAmount()
{
try
{
return Ok((await _orderRepository.CustomMadeQueryThatReturnsIQueryable()
.Select(x => new
{
CustomerId = x.CustomerId,
CustomerName = x.Customer.Name
Amount = x.Amount
})
.ToListAsync())
.GroupBy(x => x.CustomerId )
// this "async x" causes the unwanted result in my Ok() IActionResult
.Select( async x => new
{
CustomerName = x.First().CustomerName,
SumAmount = await Services.CustomerAmountService.QueryDbAndReturnResult(x.Sum(x => x.Amount))
})
));
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
结果如下:
{"1":[{"result":{"customerName":"VeryNiceCustomer","amount":1.0},"id":1269,"exception":null,"status":5,"isCanceled":false,"isCompleted":true,"isCompletedSuccessfully":true,"creationOptions":0,"asyncState":null,"isFaulted":false}]}
但是想要的结果和没有“async x”和异步函数的结果(所以只返回'1'并且根本不做进一步的操作)看起来像这样:
{"1":[{"customerName":"VeryNiceCustomer","amount":1}]}
我想知道我可以更改什么以始终获得第二个结果,而不用担心返回有关操作的不必要数据?它似乎正在返回一个结果,但我只对结果的结果感兴趣(函数返回什么,而不是异步结果)
【问题讨论】:
标签: c# linq asp.net-core asynchronous