c# - .Any 导致转换为值类型 'Boolean' 失败,因为物化值为 null

标签 c# linq lambda

完整的错误信息:

The cast to value type 'Boolean' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.

代码:

 var messages = ctx.tblMessageQueue.Where(o => o.Status == status && o.Region == region);     
 //o.Status is a byte type and not nullable, o.Region is an int type and not nullable.

 if(messages != null && messages.Any()) => Triggers the Error
 {...
 }

堆栈跟踪是:

at System.Data.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader1.GetValue(DbDataReader reader, Int32 ordinal) at lambda_method(Closure , Shaper ) at System.Data.Common.Internal.Materialization.Coordinator1.ReadNextElement(Shaper shaper) at System.Data.Common.Internal.Materialization.Shaper1.SimpleEnumerator.MoveNext() at System.Linq.Enumerable.Single[TSource](IEnumerable1 source) at System.Data.Objects.ELinq.ObjectQueryProvider.b__3[TResult](IEnumerable1 sequence) at System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable1 query, Expression queryRoot) at at System.Linq.Queryable.Any[TSource](IQueryable`1 source)

最佳答案

也许您的 tblMessageQueue 表中的列值之一是 NULL,而它在实体类中的对应属性是 bool 类型。如果是这样的话,这里有两个我能想到的建议:

  1. 更正数据和表格,使其不包含或不允许 NULL
  2. 将实体类属性更新为可为空:bool?

关于c# - .Any 导致转换为值类型 'Boolean' 失败,因为物化值为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21128669/

相关文章:

node.js - 如何使用 AWS lambda 验证 S3 中的 zip 结构

c# - Newtonsoft.Json 使用 php 7.0 json_encode 数组字符串反序列化问题

c# - Linq 集合在 foreach 的下一次迭代中重置

c# - 中继器中的匿名类型 - Eval?动态的?

linq - 在这个 T-SQL 中,是否有一个不在 Linq to Entities 的子查询中

c# - 动态递归 lambda 表达式

c++ - 用 C++11 接口(interface)包装 C 回调的最佳方法是什么?

c# - 对象列表中的自动映射器

c#从客户端实时上传到服务器到amazon s3

c# - Linq 查询问题