3

I have a Job Register Table and that table doesn't have any records.

This is my LINQ code:

Dim QRecordCount = (From LC In CntxtJobDetails.JobRegistrations _
                            Where LC.JobCode <> 0 _
                            Select LC.JobCode).Max() + 1

When I execute the code above it gives me the following error:

The null value cannot be assigned to a member with type System.Decimal which is a non-nullable value type

Please tell me how can I solve this issue, I prefer VB.NET Code

NullUserException
  • 83,810
  • 28
  • 209
  • 234
Suhaibnm
  • 89
  • 2
  • 9

1 Answers1

2

You need to make sure it runs the nullable overload of Max:

Dim QRecordCount = (From LC In CntxtJobDetails.JobRegistrations _
                            Where LC.JobCode <> 0 _
                            Select CType(LC.JobCode, Decimal?)).Max() + 1

For more information, see this link: http://weblogs.asp.net/zeeshanhirani/archive/2008/07/15/applying-aggregates-to-empty-collections-causes-exception-in-linq-to-sql.aspx

And this one: Linq query with nullable sum

Community
  • 1
  • 1
Scott Stafford
  • 43,764
  • 28
  • 129
  • 177
  • 1
    I also found the MSDN topic https://social.msdn.microsoft.com/Forums/en-US/479f2823-c942-4990-adca-21e03f969a12/sum-on-empty-table-throws-invalidoperationexception?forum=linqprojectgeneral Even tho Linq works this way by design, I would say it is the wrong design as it doesn't behave as expected, if you Max a decimal and the return type of the funtion is a decimal then you expect a decimal, not a null. This design has introduced a bug into at least my code, so I would say this is bad design on the part of Linq – Luke T O'Brien Mar 22 '17 at 12:38