c# - EFCore 在前一个操作完成之前在此上下文上启动了第二个操作
问题描述
我收到了这个错误,但我无法确定真正的原因是什么,因此我无法修复它?“实体框架核心:在前一个操作完成之前在此上下文上启动了第二个操作”
上下文
private readonly ApplicationDbContext _context;
public MyController(ApplicationDbContext context)
{
_context = context;
}
此处出现错误“await _context.SaveChangesAsync();”,但该语句只执行一次。
//Find user by Id
var foundUser = await _context.Users.FindAsync(myUserId);
//Populate myUserData here
....
//If user not found, create the user
if (foundUser == null)
{
_context.Users.Add(myUserData);
await _context.SaveChangesAsync(); //<--------ERROR HERE!
}
解决方案
您正在尝试修改 foundUser ,但它没有返回,因为它是异步的。
解决此问题的更简单方法是使用 .Result ,如下所示:
if (foundUser.Result == null)
这样它将等待上一次调用的结果