简体   繁体   中英

Sequence contains no elements handling

My API has a lot of db calls so I need to handle practically every database call with FirstOrDefault or FirstOrDefaultAsync , but is there a way to do it better then

if (user == null) return NotFound();

every time I want to retrieve User row from database?

I ended up using IAsyncActionFilter , my code:

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

And ConfigureServices function

services.AddMvc(f => f.Filters.Add(new SampleAsyncActionFilter()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM