EF Core-System.InvalidOperationException:ExecuteReader需要一个打开
本文关键字:一个 InvalidOperationException Core-System ExecuteReader EF | 更新日期: 2023-09-27 17:59:44
我正在运行一个带有实体框架核心的ASP.NET Core 1.0 web应用程序。当应用程序运行了一段时间(24-48小时)时,应用程序在向任何端点或静态资源发出的每个请求时都会崩溃,并引发错误System.InvalidOperationException: ExecuteReader requires an open and available Connection. The connection's current state is closed.
。我只能通过重新启动应用程序池来从中恢复。
我正在配置这样的实体框架:
启动.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
我在owin管道中加载数据,使用的扩展方法如下:
启动.cs
app.LoadTenantData();
AppBuilderExtension.cs:
public static void LoadTenantData(this IApplicationBuilder app)
{
app.Use(async (context, next) =>
{
var dbContext = app.ApplicationServices.GetService<ApplicationDbContext>();
var club = dbContext.Clubs.Single(c => c.Id == GetClubIdFromUrl(context));
context.Items[PipelineConstants.ClubKey] = club;
await next();
});
}
由于该错误只发生在应用程序运行很长时间时,因此很难重现,但我认为这与EF错误地打开和关闭连接有关。
我该如何调试它?我是否错误地使用EF?
我遇到了同样的问题。
我认为同一个dbcontext实例很可能被多个线程并发使用。
您可能需要:services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")),ServiceLifetime.Transient);
这是一个问题。https://github.com/aspnet/EntityFramework/issues/6491
我的应用程序非常基础(写得很快,运行一次,然后忘记),所以解决上述问题的方法是简单地在执行多表插入的部分引入lock
。
public void CallGooglePlacesAPIAndSetCallback(string websiteName)
{
using (var db = new WebAnalyzerEntities())
{
IList<IRecord> addressesToBeSearched = db.Rent.Where<IRecord>(o => o.Url.Contains(websiteName) && o.SpatialAnalysis.Count == 0).ToList().Union(db.Sale.Where<IRecord>(oo => oo.Url.Contains(websiteName) && oo.SpatialAnalysis.Count == 0)).ToList();
foreach (var locationTobeSearched in addressesToBeSearched)
{
try
{
//this is where I introduced the lock
lock (_lock)
{
dynamic res = null;
using (var client = new HttpClient())
{
while (res == null || HasProperty(res, "next_page_token"))
{
var url = $"https://maps.googleapis.com/maps/api/geocode/json?address={locationTobeSearched.Address}&key={googlePlacesApiKey}&bounds=51.222,-11.0133788|55.636,-5.6582363";
if (res != null && HasProperty(res, "next_page_token"))
url += "&pagetoken=" + res["next_page_token"];
var response = client.GetStringAsync(url).Result;
JavaScriptSerializer json = new JavaScriptSerializer();
res = json.Deserialize<dynamic>(response);
if (res["status"] == "OK")
{
Tuple<decimal?, decimal?, string> coordinatesAndPostCode = ReadResponse(res["results"][0]);
if (coordinatesAndPostCode != null && coordinatesAndPostCode.Item1.HasValue && coordinatesAndPostCode.Item2.HasValue)
{
//this is the line where exception was thrown
locationTobeSearched.SpatialAnalysis.Add(new SpatialAnalysis() { Point = CreatePoint(coordinatesAndPostCode.Item1.Value, coordinatesAndPostCode.Item2.Value) });
locationTobeSearched.PostCode = coordinatesAndPostCode.Item3;
}
}
else if (res["status"] == "OVER_QUERY_LIMIT")
{
return;
}
}
}
}
}
catch (Exception e)
{
}
db.SaveChanges();
}
}
}