Home > Blockchain >  How to resolve the Cannot await in the filter expression?
How to resolve the Cannot await in the filter expression?

Time:01-08

I am following the code example from here: https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-6.0&tabs=visual-studio-code

try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException) when (!TodoItemExists(id))
            {
                return NotFound();
            }

Where as in my code, the method TodoItemExists (in my case the method name is UserExists) is async.

Code sample:

try
{
    await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException) when (!await UserExists(id))
{
    return NotFound();
}

Error: Cannot await in the filter expression

What is the correct way to write this?

CodePudding user response:

The "old" way:

try
{
    await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException) 
{
    if (!await UserExists(id)) 
      return NotFound();
    else   
      throw;
}

But you might want to return something else in the case of "the user was found but someone else modified it first" so the client can decide what to do - maybe even send the current state. Seems to me the client/user is reasonably the only thing that can resolve a "skip/overwrite/merge" choice

  •  Tags:  
  • Related