Home > Blockchain >  using Find() method with async/await
using Find() method with async/await

Time:07-28

I have sync method i MVC controller , which I want to make it async it had this in the controller

  var user = _context.Users.Find(UserId);
  cart.User = user;
  _context.SaveChanges();
 

but when I change to await ,

  var user =await _context.Users.Find(UserId);
  cart.User = user;
  _context.SaveChanges();

it gives me error

User doesnot contain definition for 'Getawaiter' and no accessible extension accepting a first argument of type User.......

but if I change it to

 var user = await _context.Users.Where(p=>p.Id==UserId).FirstOrDefaultAsync();
 cart.User = user;
 _context.SaveChanges(); 

it works fine. Cann't I use find method with async/await???

CodePudding user response:

You can't just make any method async by putting await before it. There has to be an async version of the method.

EFCore: DbSet.FindAsync()

EF: DbSet.FindAsync()

CodePudding user response:

it works fine. Cann't I use find method with async/await???

For the same reason you cannot use .FirstOrDefault() with await and decided to use .FirstOrDefaultAsync();.

The method you are looking for is called .FindAsync().

CodePudding user response:

Sorry if I write it as a response but I can't comment yet. In your .NET version FindAsync() exists? Eventually you can use that.

  • Related