[英]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我有同步方法我 MVC controller,我想让它异步它在 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.......用户不包含“Getawaiter”的定义,并且没有接受用户类型的第一个参数的可访问扩展......
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???我不能将 find 方法与 async/await 一起使用吗???
You can't just make any method async by putting await
before it.您不能通过将await
放在它之前来使任何方法异步。 There has to be an async version of the method.该方法必须有一个异步版本。
EFCore: DbSet.FindAsync() EFCore: DbSet.FindAsync()
EF: DbSet.FindAsync() EF: DbSet.FindAsync()
it works fine.它工作正常。 Cann't I use find method with async/await???我不能将 find 方法与 async/await 一起使用吗???
For the same reason you cannot use .FirstOrDefault()
with await
and decided to use .FirstOrDefaultAsync();
出于同样的原因,您不能将.FirstOrDefault()
与await
一起使用,并决定使用.FirstOrDefaultAsync();
. .
The method you are looking for is called .FindAsync()
.您正在寻找的方法称为.FindAsync()
。
Sorry if I write it as a response but I can't comment yet.对不起,如果我把它写成回复,但我还不能发表评论。 In your .NET version FindAsync()
exists?在您的 .NET 版本中存在FindAsync()
吗? Eventually you can use that.最终你可以使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.