2017-09-04 3038 views
11

我有一個使用EF Core的ASP.Net Core應用程序。EF Core發生間歇性錯誤:連接不支持MultipleActiveResultSets

我使用ASP.Net標識併爲我的應用程序的實體共享相同的DBContext。

我已將連接字符串設置爲Azure SQL數據庫以使MultipleActiveResultSet = True。

它適用於一兩天,但最終還是失敗,出現錯誤:

The connection does not support MultipleActiveResultSets.

我不認爲火星是真正的問題,因爲它的工作的頭兩天就漲。

我正在使用ASP.Net Core的內置DI來設置我的DbContext。

services.AddDbContext<AppDbContext>(options => 
    options.UseSqlServer(appDbContextConnectionString)); 

我的理解是,上面的DbContext的默認生命週期是瞬態的(每個Web請求)。

是否可以與ASP.Net Identity共享相同的DBContext,還是應該爲應用程序的實體分別指向同一個DB?

我不知道這是EF Core,ASP.Net Core還是SQL Azure配置的問題。

+0

https://github.com/aspnet/EntityFrameworkCore/issues/6491他是什麼意思「中間件是否每個請求都有一個範圍?」 –

+0

你可以分享你注入或創建你的數據庫上下文的代碼嗎? – hugoterelle

+3

您可能想要檢查連接字符串是否在運行時實際使用了「MultipleActiveResultSet = True」。只是一個猜測。 https://stackoverflow.com/questions/12690453/sql-azure-getting-an-error-there-is-already-an-open-datareader-associated-wit –

回答

0

我也一直在遇到這個問題,並且在連接字符串中設置MultipleActiveResultSet=True沒有太大的作用。

Startup.cs我的數據庫配置非常相似,你有什麼:

services.AddEntityFrameworkSqlServer() 
     .AddDbContext<MyDbContext>(options => 
      options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), 
      builder => builder.MigrationsAssembly("MyProject")), 
      ServiceLifetime.Transient 
     ); 

原來,我是越來越

The connection does not support MultipleActiveResultSets

,因爲我有幾個異步數據庫查詢訪問同一實體。因此,一個數據庫查詢將檢索一個實體,另一個將通過EF Core的新方法Include包括相同的實體。另請參閱https://stackoverflow.com/a/46164203/4336725

我有幾個異步數據庫查詢的原因是因爲EF Core目前不支持延遲加載(與EF 6不同)。 https://github.com/aspnet/EntityFrameworkCore/issues/3797

我的解決方法是用不同的明確Include()ThenInclude()定義幾個IQueryable秒。