序列不包含元素处理
Sequence contains no elements handling
我的 API 有很多数据库调用,所以我需要用 FirstOrDefault
或 FirstOrDefaultAsync
处理几乎每个数据库调用,但是有没有办法做得更好呢
if (user == null) return NotFound();
每次我想从数据库中检索用户行?
我最终使用了 IAsyncActionFilter
,我的代码:
public class SampleAsyncActionFilter : IAsyncActionFilter
{
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var result = await next();
if (result.Exception == null || result.Exception.GetType() != typeof(InvalidOperationException)) return;
result.Result = new NotFoundObjectResult("Row was not found");
result.ExceptionHandled = true;
}
}
和ConfigureServices
函数
services.AddMvc(f => f.Filters.Add(new SampleAsyncActionFilter()));
我的 API 有很多数据库调用,所以我需要用 FirstOrDefault
或 FirstOrDefaultAsync
处理几乎每个数据库调用,但是有没有办法做得更好呢
if (user == null) return NotFound();
每次我想从数据库中检索用户行?
我最终使用了 IAsyncActionFilter
,我的代码:
public class SampleAsyncActionFilter : IAsyncActionFilter
{
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var result = await next();
if (result.Exception == null || result.Exception.GetType() != typeof(InvalidOperationException)) return;
result.Result = new NotFoundObjectResult("Row was not found");
result.ExceptionHandled = true;
}
}
和ConfigureServices
函数
services.AddMvc(f => f.Filters.Add(new SampleAsyncActionFilter()));