什么可以导致EntityCommandDefinition.ExecuteStoreCommands中的EntityCommandExecutionException?

Jon*_*der 22 c# sql-server linq-to-sql

从SQL Server 2008数据库运行的C#程序中的SQL Server视图中选择字段的特定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 ...] 
Run Code Online (Sandbox Code Playgroud)

导致此异常的原因是什么?

Jon*_*der 25

这可能是由于LINQ查询试图选择目标数据库视图或表中实际不存在的字段引起的.

这种情况可能发生的一种方式(在我的情况下是问题)忽略了将最近创建的实体框架迁移部署到目标环境,该迁移将新字段添加到要查询的视图中.

另一件需要注意的是抛出的EntityCommandExecutionException的内部异常(如错误消息所示).在这种情况下,内部异常是SqlException类型并且有有用的消息Invalid column name ‘[my column name]’.

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

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


Man*_*ngh 12

这可能是由连接字符串中缺少"多个活动结果集"引起的.

多个活动结果集(MARS)是一种允许在单个连接上执行多个批处理的功能.在以前的版本中,一次只能对一个连接执行一个批处理.使用MARS执行多个批次并不意味着同时执行操作.

修理:

string connectionString = "Data Source=MSSQL1;" + 
"Initial Catalog=AdventureWorks;Integrated Security=SSPI;" +
"MultipleActiveResultSets=True";
Run Code Online (Sandbox Code Playgroud)