>
> 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;
>
>
>This indeed works. If I'm right
Sum(r => (decimal?)r.Weight)
the (decimal?) type definition applies to Sum() because Weight is defined a non nullable in my SQL table.
>
>Many thanks for your help.
Marc,
If you check my reply to Viv (I think I CCed to you?), the most secure way is:
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.
Edit: BTW (decimal?) would also apply to a decimal. i.e.:
decimal t = (decimal?)0??0;
decimal t = (decimal?)null??0;
in either case t is decimal 0.
PS: I removed the parentheses just because they were not needed.