> decimal emWeight = context.EMTransactions.Where(r => r.TransactionHeaders_Id == transactionHeaders_Id).Sum(r => (decimal?)r.Weight) ?? 0; > // decimal? emWeight = 0; > // var q = context.EMTransactions.Where(r => (r.TransactionHeaders_Id == transactionHeaders_Id)); > // if ((q.Count() == 0) == false) > // { > // emWeight = q.Sum(r => r.Weight); > // } > decimal detailsWeight = context.TransactionDetails.Where(r => (r.TransactionHeaders_Id == transactionHeaders_Id)).Sum(r => r.Weight); > return emWeight - detailsWeight; >>
Sum(r => (decimal?)r.Weight)the (decimal?) type definition applies to Sum() because Weight is defined a non nullable in my SQL table.
decimal emWeight = context.EMTransactions.Where(r => r.TransactionHeaders_Id == transactionHeaders_Id).Sum(r => (decimal?)r.Weight) ?? 0; decimal detailsWeight = context.TransactionDetails.Where(r => r.TransactionHeaders_Id == transactionHeaders_Id).Sum(r => (decimal?)r.Weight) ?? 0; return emWeight - detailsWeight;This way you do not have to think of if the underlying field r.Weight is nullable or not. Otherwise it would not only depend on underlying field is nullable or not but if there are matching records to sum as well.