代码之家  ›  专栏  ›  技术社区  ›  thebenman

用实体框架计算两列空值之差

  •  0
  • thebenman  · 技术社区  · 6 年前

    说我有张桌子说 student 有两个可为空的十进制列

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

    135 - 35= 100

    但我现在的问题是 (85 - NULL) + (NULL - 5) + (50 - 30) = 0 - 0 + 20 = 20

    我会编写一个SQL查询,比如

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

    但我不确定这在使用EF时是如何实现的

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

    我可以用两个分开的 Sum

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

    如何使用单个 总和

    1 回复  |  直到 6 年前
        1
  •  1
  •   Drag and Drop    6 年前

    你在找 null coaliscing operator ?? . 如果左侧部分为空,则返回右侧部分:

    int exemple = null ?? -1;
    

    此处,0作为null的默认值:

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