gpt4 book ai didi

c# - Entity Framework 7(核心): DataReader must be closed exception

转载 作者:太空狗 更新时间:2023-10-30 00:18:29 26 4
gpt4 key购买 nike

我正在使用 EF7(EF 核心)。当我尝试以单一方法更新这样的数据库项目时...

using (var db = new DBContext())
{
var deadSources =
await
db.Source.Where(x => !x.Item.Any())
.ToListAsync();
foreach (var srs in deadSources)
{
srs.InspectionFailed = true;
srs.InspectionFailedDescription = "ERROR";
}
await db.SaveChangesAsync();
}

using (var db = new DBContext())
{
var aliveSources =
await
db.Source.Where(x => x.Item.Any())
.ToListAsync();
foreach (var srs in aliveSources)
{
srs.InspectionFailed = false;
srs.InspectionFailedDescription = string.Empty;
}
await db.SaveChangesAsync(); // Exception here
}

...抛出此异常:

There is already an open DataReader associated with this Command which must be closed first.

我怎样才能避免这种情况?每个数据库请求都有两个不同的上下文,所以我不明白为什么会这样。

最佳答案

同一个 DbContext 是否有一个、两个或多个实例并不重要,数据库服务端存在每个连接一个数据读取器的限制,因此您需要在连接字符串中启用 MultipleActiveResultSets 选项:

<add name="XYZ" connectionString="Server=SERVER;Database=DATABASE;
Trusted_Connection=SSPI;MultipleActiveResultSets=True;"
providerName="System.Data.SqlClient"/>

关于c# - Entity Framework 7(核心): DataReader must be closed exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35774111/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com