简体   繁体   中英

Calculating the difference between two column with NULL's using Entity Framework

Say I have a table say student with two nullable decimal columns like this

   A       B
-------|--------
   85  |  NULL
  NULL |  5
   50  |  30

I wish to calculate the difference between the sum of two columns A and B. ie) 135 - 35= 100

But with my current query i get (85 - NULL) + (NULL - 5) + (50 - 30) = 0 - 0 + 20 = 20

I'd write a SQL query like

select SUM(ISNULL(A, 0) - ISNULL(B, 0)) from student --100

But I'm not sure how this would be achievable in using EF

I currently write the below query which doesn't coalesce the null to zero.

var result = context.student.Sum(m=> m.A - m.B); // 20

I could use two separate Sum , but I prefer to write it in a single sum statement

var result = context.student.Sum(m=> m.A) - context.student.Sum(m=> m.B) 

How do I achieve this using a single Sum

You are looking for the null coaliscing operator ?? . If the part at it's left is null it return the right part:

int exemple = null ?? -1;

Here, with 0 as default value for null:

var result = context.student.Sum(m=> (m.A??0) - (m.B??0));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM