Blazor等待ef核心完成请求 [英] Blazor wait for ef core to finish request
问题描述
所以现在我得到一个
Error: System.InvalidOperationException: A second operation was started on this context before a previous operation completed.
因为blazor似乎不尊重当前请求.
Because blazor doesn't seem to respect the current request.
我正在做的事情是这样的:
What I am doing is something like this:
FirstComponent.razor
FirstComponent.razor
@inject IService _service; // abstracted service that calls EF
<layout> // layout stuff here
<SecondComponent /> // second blazor component
</layout>
@code {
protected override async Task OnInitializeAsync()
{
var getSomething = await _service.OnInitializedAsync();
}
}
SecondComponent.razor
SecondComponent.razor
@inject IService _service; // abstracted service that calls EF
@code {
protected override async Task OnInitializedAsync()
{
var getSomething = await _service.GetSomething();
}
}
因此,我将实体拆分为多个子组件以进行编辑.现在我有一个父母".调用所有这些子组件的组件.
So I split my entity in to multiple sub-components for editing it. Now I have one "parent" component that calls all these sub-components.
我的 IService
看起来像这样.
public interface IService
{
public Task<Something> GetSomething();
}
internal class Service : IService
{
private readonly SomethingRepository _repo;
public Service(SomethingRepository repo)
{
_repo = repo;
}
public async Task<Something> GetSomething() => _repo.GetAsync();
}
internal SomethingRepository
{
private readonly AppDbContext _context;
public SomethingRepository(AppDbContext context)
{
_context = context;
}
public async Task<Something> GetAsync() => ...;//implementation of whatever
}
我正在通过 AddDbContext
将我的 AppDbContext
添加到服务集合中,并通过 AddScoped
I am adding my AppDbContext
to the service collection with AddDbContext
and my services and repositories with AddScoped
推荐答案
将此添加到您的连接字符串"MultipleActiveResultSets = true"
Add this to your connection string "MultipleActiveResultSets=true"
请注意,在编写服务器代码时,我总是在Db服务上使用Transient进行DI.我从一位MS工程师那里学到了这一点,请仔细阅读这里的评论.
As a side note, when writing server code, I always use Transient on my Db services for DI. I learnt this from a MS engineer, go figure, reading the comments here.
这篇关于Blazor等待ef核心完成请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!