Reputation: 811
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?
Upvotes: 5
Views: 2256
Reputation: 78262
Why not just check for the null?
return _projectDetail.ExpenditureDetails.Where(detail =>
detail.ProgramFund == _programFund &&
detail.Expenditure.User == _creditCardHolder
).Sum(detail => {
var a = detail.ExpenditureAmounts.FirstOrDefault(
amount => amount.isCurrent && !amount.requiresAudit
);
return a != null ? a.CommittedMonthlyRecord.ProjectedEac : 0.0m;
});
Upvotes: 3