c# - Sum of child of child in LINQ -
i need in linq query in ef6.
the master table called exam
. child examresult
. each examresult
has question
, selected answer
. each answer
has power
(0 if wrong, 1 if correct). if want know total of correct answers, run command:
var examtotal = db.exams.firstordefault(ex => ex.examid == examid).examresults.sum(er => er.answer.power);
my problem when questions not answered, , nullreferenceexception
.
some general nullchecks should trick
var exam = db.exams.firstordefault(ex => ex.examid == examid); var examtotal = exam.examresults.sum(er => er.answer?.power ?? 0);
...and in case you're not using c# 6, here's version of it:
var exam = db.exams.firstordefault(ex => ex.examid == examid); var examtotal = exam.examresults.sum(er => er.answer != null ? er.answer.power : 0);
Comments
Post a Comment