Bootstrap
本文主要介绍Entity Framework Core在ASP.NET Core中,多个请求中使用同一个context问题,Entity Framework Core上下文(context)不能在多线程中使用,多个请求其实就是多个线程。报错信息: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()。

引用EF Core的版本:

项目ASP.Net Core版本: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()

问题原因

EF Core的Context两个线程同时使用会报该异常; 同一请求中的两个线程,或两个请求。

解决方法

在Controller中context的中字段不要使用静态的。例如:

private readonly MyDbContext _context; //not static
public MyController(MyDbContext context) {
    _context = context;
}

并且在Startup类中ConfigureServices()中配置Context时,要使用如下方法配置:

services.AddTransient<MyContext>();

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

上述配置在每次请求时,创建EF Core Context上下文件,则不会出现多个线程使用同一个Context问题。