Comparing dates in a dynamic Where place in Linq gives an overload exception

I am trying to introduce a dynamic where clause in my Linq to SQL query, and I am getting an overload exception. Does the same expression work if it is added to a query?

qry.Where(Function(c) c.CallDate < Date.Now.AddDays(-1)) 

Any thoughts on how this works?

An exception:

 Overload resolution failed because no accessible 'Where' can be called with these arguments: Extension method 'Public Function Where(predicate As System.Func(Of Calls, Integer, Boolean)) As System.Collections.Generic.IEnumerable(Of Calls)' defined in 'System.Linq.Enumerable': Nested function does not have the same signature as delegate 'System.Func(Of Calls, Integer, Boolean)'. Extension method 'Public Function Where(predicate As System.Func(Of Calls, Boolean)) As System.Collections.Generic.IEnumerable(Of Calls)' defined in 'System.Linq.Enumerable': Option Strict On disallows implicit conversions from 'Boolean?' to 'Boolean'. Extension method 'Public Function Where(predicate As System.Linq.Expressions.Expression(Of System.Func(Of Calls, Integer, Boolean))) As System.Linq.IQueryable(Of Calls)' defined in 'System.Linq.Queryable': Nested function does not have the same signature as delegate 'System.Func(Of Calls, Integer, Boolean)'. Extension method 'Public Function Where(predicate As System.Linq.Expressions.Expression(Of System.Func(Of Calls, Boolean))) As System.Linq.IQueryable(Of Calls)' defined in 'System.Linq.Queryable': Option Strict On disallows implicit conversions from 'Boolean?' to 'Boolean'. C:\Projects\Test Projects\Encore\EncoreData.vb 59 9 Encore 

thanks

+4
source share
2 answers

Just having hit, I have not seen this before, but here you go.

It seems that the key parts are these 2 lines from your exception:

The nested function does not have the same signature as the delegate of 'System.Func (Of Calls, Integer, Boolean)'.

forbids implicit conversions from 'Boolean? to' Boolean '.

So, your function that you create seems to have a boolean? Type output, whereas where clause expects a boolean value. And the system can not do implicit conversion from logical? for boolean due to the possibility of a null value.

So, you can try writing your function with an explicit conversion. Either (boolean) or Convert.ToBool.

+3
source

I found the answer ...

c.Calldate is a type with a null value, Date.Now is not NULL. The correct expression should look like this:

 qry.Where(Function(c) c.CallDate.Value > Date.Now.AddDays(-1)) 

Exception hint:

 disallows implicit conversions from 'Boolean?' to 'Boolean' 

Pay attention to "?" after the first boolean.

Thanks for making me look more closely at the error message!

+3
source

All Articles