我正在尝试连接一个标签。如果一个字段包含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);
}
在这里,如果字段中不存在数据,则label变为
null
。我试过了
select new { label = N.Address1 ?? "?" + " | " + N.Address2 ?? "?" + " | " + N.City ?? "?", 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/