最近我們的一位測驗人員報告了我們的應用程式錯誤。此錯誤似乎與 EF 核心事務有關,但我們沒有在代碼中使用事務。但是我們根本沒有在這個應用程式上使用事務。
當多個用戶在我們的應用程式上連接時,這個問題似乎是隨機發生的。
錯誤是:
Error : System.invalidOperationException
BeginExecuteReader require the command to have a transaction when the connection assigned to the command is in a pending local transaction.
The transaction property of the command has not been initialized.
從堆疊跟蹤來看,當我們只是在一個名為“SurveyOperations”的類中執行時,就會發生此錯誤:
Survey surveyToSave = await _context.Surveys.FindAsync(id);
詳情:
_context 是在 SurveyOperations 建構式中使用 asp.net core Dependency injection 初始化的。
在 startup.cs 中,SurveyOperations 的范圍是“瞬態”,DB 連接也是如此。我們的 EF 核心呼叫 100% 是異步的。
我們在使用 OwningComponentBase 注入 SurveyOperations 的 Blazor 組件上遇到此錯誤:
@using Microsoft.Extensions.DependencyInjection
@inherits OwningComponentBase
@code{
private SurveyOperations _surveyOperations;
private Survey survey;
protected override async Task OnInitializedAsync()
{
_surveyOperations = ScopedServices.GetRequiredService<SurveyOperations>();
survey = await _surveyOperations.GetSurveyAsync(id);
}
private async Task HandleValidSubmit()
{
// Get sone data from the form on the component
await _surveyOperations.SaveSurvey(survey);
}
}
```
We suspect that EF core is reusing connections but we didn't know how to avoid that.
uj5u.com熱心網友回復:
在我看來,您的設計是錯誤的,并且 的使用OwningComponentBase并不能保護您免受在 Blazor 中使用 DbContext 引起的問題。您可以使用以下任一方法解決此問題:
@inherits OwningComponentBase<AppDbContext>
AppDbContext 是你的 DbContext
或者更好,更適合您的設計,實作 IDbContextFactory...在這種情況下,您可以像這樣配置 dbcontext:
builder.Services.AddDbContextFactory<ContactContext>(opt =>
opt.UseSqlite($"Data Source={nameof(ContactContext.ContactsDb)}.db"))
在這里看到完整的解釋:完整的解釋
在您的SurveyOperations服務中,您可以執行以下操作:
public SurveyOperations(IDbContextFactory<ContactContext> factory)
{
DbFactory = factory;
}
在您的各種方法中,您可以執行以下操作:
using var _context = DbFactory.CreateDbContext();
Survey surveyToSave = await _context.Surveys.FindAsync(id);
請注意,第二個選項呈現OwningComponentBase多余的使用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/386290.html
標籤:C# asp.net-mvc 实体框架核心 西装外套 .net-5
