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

如果字段包含null,则整个连接结果为null

  •  2
  • Ramesh  · 技术社区  · 6 年前

    我正在尝试连接一个标签。如果字段包含 null 那么整个连接结果就是 无效的

    [HttpGet]
    public ActionResult PMAByPC(string PartnerCode)
    {
        var result = (from N in _POSContext.PMAs
                      where (N.PartnerCode == PartnerCode)
                      select new 
                      { 
                          label = N.Address1 + " | " + N.Address2 + " | " + N.City, 
                          id = N.ID 
                      });
    
        return Json(result);
    }
    

    无效的 .

    select new { label = N.Address1 ?? "?" + " | " + N.Address2 ?? "?" + " | " + N.City ?? "?", id = N.ID }

    那就只需要 N.Address1 值并忽略其余字段。

    2 回复  |  直到 6 年前
        1
  •  4
  •   Ivan Stoev    6 年前

    看起来这是一种标准的SQL字符串连接行为(SqlServer数据库也会发生这种情况)。

    如果要计算连接服务器端(数据库),则需要转换 null 清空字符串 "" (或其他)使用 ?? 接线员。与您的尝试类似,但您错过了C#运算符的优先级。你写的方式相当于

    N.Address1 ??
    (
      ("?" + " | " + N.Address2) ??
      (
          ("?" + " | " + N.City) ?? "?"
      )
    )
    

    这不是我们的意图。

    您可以通过用括号括起类似的转换来避免此类问题:

    select new
    {
        label = (N.Address1 ?? "?") + " | " + (N.Address2 ?? "?") + " | " + (N.City ?? "?"),
        id = N.ID,
    } 
    
        2
  •  0
  •   Laurenz Albe    6 年前

    这是符合标准且合理的行为:如果将一个字符串与一个未知字符串连接起来,则结果是未知的。

    使用 coalesce

    coalesce(col1, '') || coalesce(col2, '')