Properly handling possible System.NullReferenceException in lambda expressions

Posted by Travis Johnson on Stack Overflow See other posts from Stack Overflow or by Travis Johnson
Published on 2010-05-04T21:49:53Z Indexed on 2010/05/04 22:48 UTC
Read the original article Hit count: 667

Filed under:
|
|
|

Here's the query in question

return _projectDetail.ExpenditureDetails
    .Where(detail => detail.ProgramFund == _programFund
         && detail.Expenditure.User == _creditCardHolder)
    .Sum(detail => detail.ExpenditureAmounts.FirstOrDefault(
        amount => amount.isCurrent && !amount.requiresAudit)
    .CommittedMonthlyRecord.ProjectedEac);

Table Structure
ProjectDetails (1 to Many) ExpenditureDetails
ExpenditureDetails (1 to Many) ExpenditureAmounts
ExpenditureAmounts (1 to 1) CommittedMonthlyRecords

ProjectedEac is a decimal field on the CommittedMonthlyRecords.

The problem I discovered in a Unit test (albeit an unlikely event), that the following line could be null:

detail.ExpenditureAmounts.FirstOrDefault(
    amount => amount.isCurrent && !amount.requiresAudit)

My original query was a nested loop, in where I would be making multiple trips to the database, something I don't want to repeat. I've looked in to what seemed like some similar questions here, but the solution didn't seem to fit.

Any ideas?

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ