在针对 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 ...]
什么原因导致出现此异常?
这可能是由于 LINQ 查询尝试选择目标数据库视图或表中实际不存在的字段导致的。
发生这种情况的一种方法(这就是我的例子中的问题)是忽略将最近创建的实体框架迁移部署到目标环境,该迁移将新字段添加到正在查询的视图中。
另一件需要注意的事情是抛出的 EntityCommandExecutionException 的内部异常(如错误消息所示)。在本例中,内部异常的类型为 SqlException 并具有有用的消息
Invalid column name ‘[my column name]’
。
因此,在运行 LINQ-to-SQL 查询时抛出 EntityCommandDefinition.ExecuteStoreCommands 处的 EntityCommandExecutionException 时需要注意的事项:
这可能是由于连接字符串中缺少“多个活动结果集”造成的。
多个活动结果集 (MARS) 是一项允许在单个连接上执行多个批处理的功能。在以前的版本中,一次只能针对单个连接执行一批。使用 MARS 执行多个批次并不意味着同时执行操作。
修复:
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
}
[Table("TableName")]
public partial class TableName: IEntity
{
//public TableName()
//{
// this.TableNames = new List<TableName>();
//}
public int Column1 { get; set; }
// public virtual ICollection<TableName> TableNames { get; set; }
}
我在实体类中将虚拟表定义注释为上述代码。后来就修好了。