【问题标题】:EFCore A second operation started on this context before a previous operation completedEFCore 在前一个操作完成之前在此上下文上启动了第二个操作
【发布时间】:2019-06-21 16:09:18
【问题描述】:

我收到了这个错误,但我无法确定真正的原因是什么,因此我无法修复它? “Entity Framework Core:在前一个操作完成之前在此上下文上启动了第二个操作”

上下文

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!
        }

【问题讨论】:

  • 可能不相关,但在这种模式下,_context 是如何处理的?
  • 上面的代码在一个方法中,我在没有“await”的情况下使用它,我添加了“await”,现在一切正常。

标签: c# asp.net-core entity-framework-core


【解决方案1】:

您正在尝试修改 foundUser ,但它没有返回,因为它是异步的。

解决此问题的更简单方法是使用 .Result,如下所示:

if (foundUser.Result == null)

这样它会等待上一次调用的结果

【讨论】:

  • 除非 foundUser 的类型有 Result 属性,我认为这个 if (foundUser.Result == null) 不会编译
猜你喜欢
  • 2021-10-22
  • 2020-12-18
  • 1970-01-01
  • 2021-04-11
  • 1970-01-01
  • 2022-01-01
  • 2020-01-22
  • 2018-11-07
  • 2020-03-13
相关资源
最近更新 更多