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

标签 c# postgresql asp.net-core entity-framework-core

我正在尝试连接标签。如果字段包含 null,则整个连接结果为 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);
}

在这里,如果字段中不存在数据,则标签将变为null

我尝试过

选择新的{ label = N.Address1 ?? “?” + "| "+ N.Address2 ?? “?” + "| "+ 北城 ?? “?”,id = N.ID}

然后它只需要 N.Address1 值并忽略其余字段。

最佳答案

看起来这是一个标准的 SQL 字符串连接行为(SqlServer 数据库也是如此)。

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

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

这不是本意。

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

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

关于c# - 如果字段包含 null,则整个连接结果为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52139861/

相关文章:

c# - DllExport:将数组数组从 Delphi 传递到 C#

c# - 从文件中提取字符串并使用 c# 保存在另一个文件中

c# - 如何刷新图像的浏览器缓存?

c# - 具有不同平台名称的.NET Core项目

c# - 是否有从 xsd 生成简单的 c# 类的工具?

sql - 不寻常的两个表连接

postgresql - 设置 Phoenix Framework 和 Ecto 以使用 UUID : how to insert the generated value?

postgresql - 批量加载具有唯一约束的 Postgres

c# - ASP.NET Core 3.0 System.Text.Json Camel Case 序列化

c# - StaticFileOptions.OnPrepareResponse 不会为 index.html 调用