我正在做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作业,但这个作业不使用相同的实体。这就是我能想到的所有相关信息。知道是什么引起的吗?


当前回答

如果你的方法返回一些东西,你可以通过放 .工作结束的结果 . wait()如果它没有返回任何东西。

其他回答

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

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

如果你的方法返回一些东西,你可以通过放 .工作结束的结果 . wait()如果它没有返回任何东西。

我也遇到过同样的问题,但原因不是上面列出的那些。我创建了一个任务,在任务内部创建了一个作用域,并要求容器获取服务。这工作得很好,但后来我在任务中使用了第二个服务,我忘记了也要求它到新的范围。因此,第二个服务使用的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();

我认为这个答案仍然可以帮助一些人,节省很多时间。我通过将IQueryable更改为List(或数组,集合…)解决了类似的问题。

例如:

var list = _context.table1.Where(...);

to

var list = _context.table1.Where(...).ToList(); //or ToArray()...

使用Startup.cs文件中的这行代码解决我的问题。 添加瞬态服务意味着每次请求该服务时,都会在您工作时创建一个新实例 与 依赖注入 服务。AddDbContext > <上下文(选项= > options.UseSqlServer (_configuration.GetConnectionString(“ContextConn”)), ServiceLifetime.Transient);