我正在尝试连接标签。如果字段包含 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 数据库也是如此)。
如果您想评估串联服务器端(数据库),则需要使用 将
运算符。与您的尝试类似,但您错过了 C# 运算符优先级。你写的方式相当于null
转换为空字符串 ""
(或其他内容) ??
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/