DBcontext 在注册为 Scoped 时正在共享

DBcontext is getting shared while being registered as Scoped

我正在尝试从 ef6 迁移到 ef core 并开始遇到以下问题

System.InvalidOperationException: 'A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext, however instance members are not guaranteed to be thread safe. This could also be caused by a nested query being evaluated on the client, if this is the case rewrite the query avoiding nested invocations.'

在:

_dbContext
    .Query<EntityModel>()
    .FromSql(query, new SqlParameter("@userId", userId))
    .ToList();

我通过在连接字符串中添加 MultipleActiveResultSets=true 解决了这个问题。

示例:

string connectionString = "Data Source=MSSQL1;" +   
  "Initial Catalog=AdventureWorks;Integrated Security=SSPI;" +  
  "MultipleActiveResultSets=True";

发件人:https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/enabling-multiple-active-result-sets

只需将其添加到您的 appsettings.json 连接字符串中