Whats wrong with the below query, I am getting this error:
Nullable object must have a value.
Dim subscriptionUsers = From inv In dataContext.Invoices.ToList Join u In dataContext.Users _
On inv.Subscription Equals u.Subscription _
Where inv.Id.Value = invoiceID _
And Not u.Fund.Title.Contains("AGM") _
And DirectCast(IIf(Not u.EndDate.HasValue, IIf(u.StartDate.Value <= inv.EndDate.Value, True, False), _
IIf((u.StartDate.Value >= inv.StartDate.Value And u.StartDate.Value <= inv.EndDate.Value) Or _
(u.EndDate.Value >= inv.StartDate.Value And u.EndDate.Value <= inv.EndDate.Value) Or _
(u.StartDate.Value < inv.StartDate.Value And u.EndDate.Value > inv.EndDate.Value), True, False)), Boolean) _
Group By Key = u.Fund.Title Into Group _
Select Fund = Key, UsersCount = Group.Count, Users = Group.ToList, _
SubFunds = (From a In dataContext.Allocations Where a.Fund.Title = Key Select a.Department.Title Distinct)
If I remove the u.EndDate.Value in the condition then it works fine.
Here is the stack trace:
at System.Nullable1.get_Value()2 $VB$It)
at SDBReports.InvoiceAllocationReportUserControl._Lambda$__4(VB$AnonymousType_0
at System.Linq.Enumerable.WhereEnumerableIterator1.MoveNext()2.Create[TSource](IEnumerable
at System.Linq.Lookup1 source, Func2 keySelector, Func2 elementSelector, IEqualityComparer1 comparer)
at System.Linq.GroupedEnumerable4.GetEnumerator()2.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator
at System.Linq.SystemCore_EnumerableDebugView`1.get_Items()
p.s. I have used SPMetal to generate the entity classes on SharePoint lists.
For more clarity:
do not get confused with u.EndDate.Value and inv.EndDate.Value
here is the true part for u.EndDate.Hasvalue:
IIf((u.StartDate.Value >= inv.StartDate.Value And u.StartDate.Value <= inv.EndDate.Value) Or _
(u.EndDate.Value >= inv.StartDate.Value And u.EndDate.Value <= inv.EndDate.Value) Or _
(u.StartDate.Value < inv.StartDate.Value And u.EndDate.Value > inv.EndDate.Value), True, False)
and here is the false part
IIf(u.StartDate.Value <= inv.EndDate.Value, True, False)
Use
Ifinstead ofIIf. This is short-circuited (like C#’s conditional operator) and will work because the conditions are only evaluated ifHasValueisTrue.IIfis deprecated. Never use it.Furthermore, an expression like
If(condition, True, False)is nonsensical. Replace it with justcondition.Finally, you need to use
AndAlsoinstead ofAnd– once again, for short-circuiting to happen. In fact, always useAndAlsoandOrElsein conditionals. UseAndandOronly when doing bit operations.The
DirectCastis also unnecessary.This leaves us with a much simplified expression:
But this expression is still much too complex. You should split this up but first assigning the values inside the nullables to some temporary variable using
Letinside the query.