由于实体对象的值为null,导致将cast转换为布尔类型值失败

3

完整错误信息:

将实例化的值类型“Boolean”转换失败,因为该值为空。结果类型的泛型参数或查询必须使用可空类型。

代码:

 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
 {...
 }

StackTrace是:

在System.Data.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal)中,lambda_method(Closure, Shaper), 在System.Data.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)中, 在System.Data.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()中, 在System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)中, 在System.Data.Objects.ELinq.ObjectQueryProvider.b__3[TResult](IEnumerable`1 sequence)中, 在System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)中, 在System.Linq.Queryable.Any[TSource](IQueryable`1 source)。


1
请确保使用LINQ提供程序标记问题。 - user2864740
1
如果您有任何问题,请@user3196525保持响应。 - PawanS
3个回答

1
也许你的tblMessageQueue表中的某个列值是NULL,而实体类中相应的属性类型为bool。如果是这种情况,我有两个建议:
  1. 更正数据和表格,使其不包含或允许NULL
  2. 将实体类属性更新为可空:bool?

0

我认为你需要类似于这个的东西:

var messages = ctx.tblMessageQueue.Where(o => o.Status == status && o.Region == region)
                                  .Where(o => o.Status != null);

我不确定语法,但你只需要确保空状态消息不会进入新变量。

这里有一个例子/类似的问题 - Lambda表达式中的多个Where子句


0

检查一下你的 Message 表中的其他属性是否有空值,如果你的 Message 表包含可为空的整数,则应该考虑将你的 Message 实体类改为“int?”类型。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接