【发布时间】:2019-10-11 18:17:45
【问题描述】:
我正在创建一个服务器端 Blazor 应用程序。以下代码在Startup.cs中。
services.AddDbContext<MyContext>(o => o.UseSqlServer(Configuration.GetConnectionString("MyContext")), ServiceLifetime.Transient);
services.AddTransient<MyViewModel, MyViewModel>();
在 ViewModel 中:
public class MyViewModel : INotifyPropertyChanged
{
public MyViewModel(MyContext myContext)
{
_myContext = myContext;
}
public async Task<IEnumerable<Dto>> GetList(string s)
{
return await _myContext.Table1.where(....)....ToListAsync();
}
在剃刀文件中。
@inject ViewModels.MyViewModel VM
<input id="search" type="text" @bind="search" />
<input id="search" type="button" value="Go" @onclick="SearchChanged" />
@code {
string search = "";
int currentCount = 0;
async void SearchChanged() {
currentCount++;
dtos = GetList(search);
}
}
但是,有时点击搜索按钮时会出现以下错误?
System.InvalidOperationException: '在前一个操作完成之前,在此上下文上启动了第二个操作。这通常是由使用相同 DbContext 实例的不同线程引起的。有关如何避免 DbContext 线程问题的更多信息,请参阅https://go.microsoft.com/fwlink/?linkid=2097913。'
【问题讨论】:
-
也许,在第一个请求完成之前禁用搜索按钮。还是取消第一个异步搜索请求,然后发送新请求?
标签: c# entity-framework entity-framework-core blazor blazor-server-side