using Find() method with async/await

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???

>Solution :

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()

Leave a Reply