DeeArgee
DeeArgee

Reputation: 172

Queryable.Any() returning null?

I have a database lookup like:

var configs = dbData.Configs.Where(e => headers.Contains(e.headerId) && e.flag == "true");
if(configs.Any())
{ ... }

where configs is returned as an IQueryable type. I sometimes get this error:

System.InvalidOperationException: 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. at System.Data.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader1.GetValue(DbDataReader reader, Int32 ordinal) at System.Data.Common.Internal.Materialization.Shaper.GetColumnValueWithErrorHandling[TColumn](Int32 ordinal) 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.Linq.Queryable.Any[TSource](IQueryable`1 source)

It happens in production, seemingly randomly and I haven't been able to reproduce it in development.

EDIT TO ADD: The Config type has a foreign key constraint, if the Boolean type is being cast from that, I don't know. There is no Boolean in the Config type created by Entity Framework and there is no Boolean type in Sql Server anyway.

Upvotes: 2

Views: 1286

Answers (2)

Steve Ruble
Steve Ruble

Reputation: 3895

Here's my theory, based on the fact that e.flag is a nullable column: I think that you're getting this error when e.flag is null, because the null value propagates through your predicate and makes it end up being null on the SQL side, even though at compile time the types of the C# expression is bool not bool?. When EF tries to materialize the value it throws.

If I'm right, changing the predicate to the following will fix it:

var configs = dbData.Configs.Where(e => headers.Contains(e.headerId) && (e.flag ?? "") == "true");

Upvotes: 0

Servy
Servy

Reputation: 203835

You have some database column in your Configs table that has a nullable boolean type, but the C# entity you are mapping the table entry to is defined as using a non-nullable boolean. When the C# entity is being populated by the query provider, when it runs into a null value, it throws this exception. You need to update the entity object so that the column in question is of the proper type.

Upvotes: 2

Related Questions