我正在做ASP。Net Core 2.0项目使用实体框架核心

<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.1" />
  <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.0"/>

在我的一个列表方法中,我得到了这个错误:

InvalidOperationException: A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.
Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()

这是我的方法:

    [HttpGet("{currentPage}/{pageSize}/")]
    [HttpGet("{currentPage}/{pageSize}/{search}")]
    public ListResponseVM<ClientVM> GetClients([FromRoute] int currentPage, int pageSize, string search)
    {
        var resp = new ListResponseVM<ClientVM>();
        var items = _context.Clients
            .Include(i => i.Contacts)
            .Include(i => i.Addresses)
            .Include("ClientObjectives.Objective")
            .Include(i => i.Urls)
            .Include(i => i.Users)
            .Where(p => string.IsNullOrEmpty(search) || p.CompanyName.Contains(search))
            .OrderBy(p => p.CompanyName)
            .ToPagedList(pageSize, currentPage);

        resp.NumberOfPages = items.TotalPage;

        foreach (var item in items)
        {
            var client = _mapper.Map<ClientVM>(item);

            client.Addresses = new List<AddressVM>();
            foreach (var addr in item.Addresses)
            {
                var address = _mapper.Map<AddressVM>(addr);
                address.CountryCode = addr.CountryId;
                client.Addresses.Add(address);
            }

            client.Contacts = item.Contacts.Select(p => _mapper.Map<ContactVM>(p)).ToList();
            client.Urls = item.Urls.Select(p => _mapper.Map<ClientUrlVM>(p)).ToList();
            client.Objectives = item.Objectives.Select(p => _mapper.Map<ObjectiveVM>(p)).ToList();
            resp.Items.Add(client);
        }

        return resp;
    }

我有点迷失,特别是因为当我在本地运行它时,它可以工作,但当我部署到我的登台服务器(IIS 8.5)时,它会给我这个错误,并且它正常工作。在我增加了其中一个模型的最大长度后,错误开始出现。我还更新了相应视图模型的最大长度。还有很多类似的列表方法,它们都很有效。

我有一个正在运行的Hangfire作业,但这个作业不使用相同的实体。这就是我能想到的所有相关信息。知道是什么引起的吗?


当前回答

有一些Async函数,但是你没有在它之前调用await。在调用该函数之前查找并添加await将对您有所帮助。

其他回答

我也遇到过同样的问题,但原因不是上面列出的那些。我创建了一个任务,在任务内部创建了一个作用域,并要求容器获取服务。这工作得很好,但后来我在任务中使用了第二个服务,我忘记了也要求它到新的范围。因此,第二个服务使用的DbContext已经被处理了。

Task task = Task.Run(() =>
    {
        using (var scope = serviceScopeFactory.CreateScope())
        {
            var otherOfferService = scope.ServiceProvider.GetService<IOfferService>();
            // everything was ok here. then I did: 
            productService.DoSomething(); // (from the main scope) and this failed because the db context associated to that service was already disposed.
            ...
        }
    }

我应该这样做的:

var otherProductService = scope.ServiceProvider.GetService<IProductService>();
otherProductService.DoSomething();

在某些情况下,当调用没有await关键字的异步方法时,会发生此错误,这可以通过在方法调用之前添加await来简单地解决。然而,答案可能与上述问题无关,但它可以帮助解决类似的错误。

如果您创建了迁移(Add-Migration),但忘记实际更新数据库(update - database),也可能出现此错误。

我知道这个问题在两年前就被问到过,但我刚刚遇到过这个问题,我使用的修复程序真的很有帮助。

如果你用同一个Context做两个查询,你可能需要删除AsNoTracking。如果你使用AsNoTracking,你会为每次读取创建一个新的数据读取器。两个数据读取器不能读取相同的数据。

我也犯了同样的错误。发生这种情况是因为我调用了一个构造为公共异步void的方法…而不是公共async任务....