【发布时间】:2026-02-22 04:50:02
【问题描述】:
我正在使用实体框架,有时我会收到此错误。
EntityCommandExecutionException
{"There is already an open DataReader associated with this Command which must be closed first."}
at System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands...
即使我没有进行任何手动连接管理。
此错误间歇性发生。
触发错误的代码(为便于阅读而缩短):
if (critera.FromDate > x) {
t= _tEntitites.T.Where(predicate).ToList();
}
else {
t= new List<T>(_tEntitites.TA.Where(historicPredicate).ToList());
}
使用 Dispose 模式以每次打开新连接。
using (_tEntitites = new TEntities(GetEntityConnection())) {
if (critera.FromDate > x) {
t= _tEntitites.T.Where(predicate).ToList();
}
else {
t= new List<T>(_tEntitites.TA.Where(historicPredicate).ToList());
}
}
还是有问题
如果连接已经打开,为什么 EF 不重用它。
【问题讨论】:
-
我意识到这个问题很古老,但我很想知道您的
predicate和historicPredicate变量是什么类型。我发现如果你将Func<T, bool>传递给Where(),它会编译并且有时会工作(因为它在内存中执行“位置”)。您应该做的是将Expression<Func<T, bool>>传递给Where()。
标签: linq entity-framework sql-server-2008