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

标签 c# sql-server linq-to-sql

在针对 SQL Server 2008 数据库运行的 C# 程序中,从 SQL Server View 中选择字段的特定 LINQ-to-SQL 查询在我的本地开发环境中运行良好,但在暂存环境中运行时会产生异常:

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 查询试图选择目标数据库 View 或表中实际不存在的字段造成的。

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

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

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

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

关于c# - 什么会导致 EntityCommandDefinition.ExecuteStoreCommands 中的 EntityCommandExecutionException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30785019/

相关文章:

c# - PCL 中的 TPL 和监视器

c# - 使用 Ping 时蓝屏

sql-server - T-SQL 匹配特殊字符。 Pre 应该匹配 Pré

php - 表的 SQL 重新排序索引

sql-server - 什么是 SQL Server Rand 函数算法?

c# - 返回匿名类型的简单方法(使使用 LINQ 的 MVC 成为可能)

.net - 此SqlTransaction已完成;它不再可用

C# Automapper IQueryable - LINQ 2 SQLite - 查询仅返回父项,嵌套子项始终为 null

c# - 使用 P/Invoke 有什么缺点

c# - 当我找不到逗号时如何将逗号更改为点