什么会导致 EntityCommandDefinition.ExecuteStoreCommands 中的 EntityCommandExecutionException?

What can cause an EntityCommandExecutionException in EntityCommandDefinition.ExecuteStoreCommands?

一个特定的 LINQ-to-SQL 查询从 C# 程序 运行 中的 SQL 服务器视图中选择字段,针对 SQL Server 2008 数据库,其中运行 在我的本地开发环境中很好,在暂存环境中 运行 时产生异常:

Exception Message: An error occurred while executing the command definition. See the inner exception for details. 

Exception Trace: System.Data.Entity.Core.EntityCommandExecutionException 
at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) 
at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues) 
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) 
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.b__5() 
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation) 
at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) 
at System.Data.Entity.Core.Objects.ObjectQuery`1..GetEnumerator>b__0() 
at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext() 
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) 
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) 
at [my code ...] 

是什么原因导致此异常发生?

这可能是由于 LINQ 查询试图 select 目标数据库视图中实际不存在的字段或 table。

发生这种情况的一种方式(这是我的问题)是忽略将最近创建的 Entity Framework 迁移部署到目标环境,该迁移将新字段添加到正在查询的视图中。

另一件要看的事情是抛出的 EntityCommandExecutionException 的内部异常(如错误消息所建议的)。在这种情况下,内部异常是 SqlException 类型并且有帮助消息 Invalid column name ‘[my column name]’.

因此,在 运行 LINQ-to-SQL 查询时抛出 EntityCommandDefinition.ExecuteStoreCommands 处的 EntityCommandExecutionException 时需要注意的事项:

  • 检查内部异常(根据外部异常错误消息的建议)。
  • 确保所有 Entity Framework 迁移已部署到目标环境(如果正在使用 EF)。
  • 检查并查看查询是否正在尝试 select 不存在的字段。

这可能是由于连接字符串中缺少 "Multiple Active Result Sets"

Multiple Active Result Sets (MARS) is a feature that allows the execution of multiple batches on a single connection. In previous versions, only one batch could be executed at a time against a single connection. Executing multiple batches with MARS does not imply simultaneous execution of operations.

修复:

string connectionString = "Data Source=MSSQL1;" + 
"Initial Catalog=AdventureWorks;Integrated Security=SSPI;" +
"MultipleActiveResultSets=True";

我帮助访问了本地属性喜欢。异常:

foreach (var myTableObject in context.Table)
{
    // Exception
}


foreach (var myTableObject in context.Table.Local)
{
    // No exception
}