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


当前回答

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

其他回答

为这个错误添加另一个可能的解决方案,以防它帮助到某人。

在我的情况下,问题是在查询中使用nav属性,就像这样:

var selectedOrder = dbContext.Orders.Where(x => x.Id == id).Single();
var relatedOrders = dbContext.Orders.Where(x => x.User.Id == selectedOrder.User.Id).ToList();

问题是在查询中使用selectedOrder.User.Id。如果User nav属性还没有被加载,EF将在试图执行查询的过程中尝试延迟加载该属性,它认为这是试图开始第二个操作。解决方案是为selectedOrder.User创建一个单独的变量。Id,以确保在查询开始之前加载了查询所需的信息:

var selectedOrder = dbContext.Orders.Where(x => x.Id == id).Single();
var userId = selectedOrder.User.Id;
var relatedOrders = dbContext.Orders.Where(x => x.User.Id == userId).ToList();

你可以使用SemaphoreSlim来阻止下一个尝试执行EF调用的线程。

static SemaphoreSlim semSlim = new SemaphoreSlim(1, 1);

await semSlim.WaitAsync();
try
{
  // something like this here...
  // EmployeeService.GetList(); or...
  var result = await _ctx.Employees.ToListAsync();
}
finally
{
  semSlim.Release();
}

在某些情况下,当调用没有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();

我不确定你是否使用IoC和依赖注入来解决你的DbContext可能被使用的地方。如果你使用了。net Core(或任何其他IoC- container)的原生IoC,并且你得到了这个错误,请确保将DbContext注册为Transient。做

services.AddDbContext<MyContext>(ServiceLifetime.Transient);

OR

services.AddTransient<MyContext>();

而不是

services.AddDbContext<MyContext>();

AddDbContext将上下文作为作用域添加,这在处理多线程时可能会带来麻烦。

当使用异步lambda表达式时,async / await操作也会导致这种行为。

将其添加为瞬态也有其缺点。你不能在多个使用上下文的类上修改某个实体,因为每个类都有自己的DbContext实例。

对此的简单解释是,DbContext实现不是线程安全的。你可以在这里阅读更多相关内容