【问题标题】:Entity Framework ExecuteStoreCommands Exception during FirstOrDefault methodFirstOrDefault 方法期间的实体框架 ExecuteStoreCommands 异常
【发布时间】:2017-11-29 21:40:42
【问题描述】:

有时,在调试一些较旧的应用程序代码时,我们会收到异常。

这是有问题的代码行:

XMLReferenceSequence lastXml = (from xml in _entities.XMLReferenceSequences
                                        where xml.ServiceId == aService.Id
                                        where xml.SourceTypeId == ETrainsSourceType.SOURCE_RAIL_XML
                                        orderby xml.ReferenceDateTime descending
                                        select xml).FirstOrDefault();

应该注意的是,代码在大多数情况下都可以正常工作,而这种情况很少发生。

任何关于如何解决此问题的想法将不胜感激。是否正在考虑重新格式化代码以在 FirstOrDefault() 之前先执行 ToList()?

异常的堆栈跟踪:


错误处理铁路记录。 :在 System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand,CommandBehavior 行为) 在 System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext 上下文,ObjectParameterCollection 参数值) 在 System.Data.Entity.Core.Objects.ObjectQuery1.<>c__DisplayClass7.<GetResults>b__6() at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) 在 System.Data.Entity.Core.Objects.ObjectQuery1.<>c__DisplayClass7.<GetResults>b__5() at System.Data.Entity.Infrastructure.DbExecutionStrategy.Execute[TResult](Func1 操作) 在 System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable1 forMergeOption) 在 System.Data.Entity.Core.Objects.ObjectQuery1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0() at System.Data.Entity.Internal.LazyEnumerator1.MoveNext() 在 System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source) at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__1[TResult](IEnumerable1 序列) 在 System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable1 query, Expression queryRoot) at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression) at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression) at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable1 源) 在 CHO.ETrains.Business.ETrainsManager.MovementProcessingFromRailList(ETrainFeedDto aFeed) 在 F:\agent_work\4\s\CHO.ALL\Business\CHO.ETrains.Business\ETrainsManager.cs:line 1961 在 F:\agent_work\4\s\CHO.ALL\Business\CHO.ETrains.Business\ETrainsManager.cs 中的 CHO.ETrains.Business.ETrainsManager.ProcessMessageOffServiceBus(ETrainFeedDto eTrainFeed, RequestDto req, HashSet`1& changesDetected, String schemaDir) :379行


收到无法处理的 Xml 消息:System.Data.Entity.Core.EntityCommandExecutionException:执行命令定义时发生错误。有关详细信息,请参阅内部异常。 ---> System.Data.SqlClient.SqlException:执行超时已过期。在操作完成之前超时时间已过或服务器没有响应。 ---> System.ComponentModel.Win32Exception:等待操作超时 --- 内部异常堆栈跟踪结束 --- 在 System.Data.SqlClient.SqlConnection.OnError(SqlException 异常,布尔型 breakConnection,Action1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) 在 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj,布尔调用者HasConnectionLock,布尔异步关闭) 在 System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,SqlCommand cmdHandler,SqlDataReader dataStream,BulkCopySimpleResultSet bulkCopyHandler,TdsParserStateObject stateObj,Boolean & dataReady) 在 System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() 在 System.Data.SqlClient.SqlDataReader.get_MetaData() 在 System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,RunBehavior runBehavior,字符串 resetOptionsString,Boolean isInternal,Boolean forDescribeParameterEncryption) 在 System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior,RunBehavior runBehavior,布尔 returnStream,布尔异步,Int32 超时,任务和任务,布尔异步写入,布尔 inRetry,SqlDataReader ds,布尔 describeParameterEncryptionRequest) 在 System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior,RunBehavior runBehavior,布尔 returnStream,String 方法,TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext1 c) 在 System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func3 操作,TInterceptionContext 拦截上下文,Action3 executing, Action3 执行) 在 System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand 命令,DbCommandInterceptionContext 拦截上下文) 在 System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior 行为) 在 System.Data.Common.DbCommand.ExecuteReader(CommandBehavior 行为) 在 System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand,CommandBehavior 行为) --- 内部异常堆栈跟踪结束 --- 在 System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand,CommandBehavior 行为) 在 System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext 上下文,ObjectParameterCollection 参数值) 在 System.Data.Entity.Core.Objects.ObjectQuery1.<>c__DisplayClass7.<GetResults>b__6() at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) 在 System.Data.Entity.Core.Objects.ObjectQuery1.<>c__DisplayClass7.<GetResults>b__5() at System.Data.Entity.Infrastructure.DbExecutionStrategy.Execute[TResult](Func1 操作) 在 System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable1 forMergeOption) 在 System.Data.Entity.Core.Objects.ObjectQuery1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0() at System.Data.Entity.Internal.LazyEnumerator1.MoveNext() 在 System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source) at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__1[TResult](IEnumerable1 序列) 在 System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable1 query, Expression queryRoot) at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression) at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression) at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable1 源) 在 CHO.ETrains.Business.ETrainsManager.MovementProcessingFromRailList(ETrainFeedDto aFeed) 在 F:\agent_work\4\s\CHO.ALL\Business\CHO.ETrains.Business\ETrainsManager.cs:line 1961 在 F:\agent_work\4\s\CHO.ALL\Business\CHO.ETrains.Business\ETrainsManager.cs 中的 CHO.ETrains.Business.ETrainsManager.ProcessMessageOffServiceBus(ETrainFeedDto eTrainFeed, RequestDto req, HashSet`1& changesDetected, String schemaDir) :第393行 在 F:\agent_work\4\s\CHO.WebJobs\CHO.WebJobs.xmlReceive\MessageProcessor.cs: 102 行中的 CHO.WebJobs.xmlReceive.MessageProcessor.ProcessBrokeredMessage(BrokeredMessage msg) 处

【问题讨论】:

  • 似乎第二个where 应该是&amp;&amp;,但显然这不是问题所在。 ToList() 呼叫是否解决了问题,还是仍然存在?
  • 嗨 Rufus,我还没有尝试过单独的 ToList。只是想看看有没有人以前见过这个。我可能会改变&&的位置。也许多个 where 语句也使查询复杂化。我想我在某处读过 EF 可能会将其变成多个子查询。
  • var lastXmlRecord = _entities.XMLReferenceSequences .Where(x => x.TrainServiceId == aService.Id) .Where(x => x.SourceTypeId == ETrainsSourceType.SOURCE_RAIL_XML) .OrderByDescending(x => x.ReferenceDateTime) .ToList() .FirstOrDefault();
  • 更改为上述代码,更改为方法语法,并在 ToList 中敲击以确保安全。还围绕它添加了额外的日志记录。看看会发生什么...

标签: c# entity-framework linq


【解决方案1】:

您的错误消息表明您的方法未能及时执行。

System.Data.SqlClient.SqlException:执行超时已过期。这 在操作完成之前经过的超时时间或 服务器没有响应

Sql Connections 连接有一个CommandTimeout 属性,默认为30 秒。如果您的查询未在此时间内完成,则会引发上述异常。如果您知道您有一个可能超过此限制的长时间运行的查询,则可以在连接字符串中增加此值。看到这个:https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.commandtimeout(v=vs.110).aspx

理想情况下,您可以通过确定是您的查询还是其他查询导致问题来解决此问题。如果是您的查询,则使用维护计划优化数据和/或创建索引可以加快查询速度。

另一个潜在危险是长时间运行的查询会锁定您从中提取数据的表之一。如果是这种情况,您可以执行一个查询,该查询要求您提取的数据没有锁定。这篇文章展示了如何做这个实体框架。 Entity Framework with NOLOCK

【讨论】:

  • 谢谢伙计,出于某种原因,我的眼球甚至没有看到超时。我深陷其中,认为它比这更险恶。
猜你喜欢
  • 2016-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多