如何在字符串插值C#中保留空值



我想保留空值(将它们插入DB(,同时将它们作为字符串传递给C#代码中的sql变量。

var valString = new StringBuilder();
//somevalue is null at this point
valString.Append($"({id}, " +$"'{SomeValue}')");

字符串插值返回的是SomeValue=>"的emptyString,而不是null。我想在字符串插值中保留该null,并将其传递给查询字符串。有可能吗?

如果SomeValue不为null,则使用SomeValue,如果为null,则使用null。

var valString = new StringBuilder();
//somevalue is null at this point
valString.Append($"({id}," + (SomeValue == null ? "NULL" : $"'{SomeValue}'"));

您可以按如下方式执行此操作:

var valString = new StringBuilder();
valString.Append($"({id}, " +$"'{SomeValue ?? "null"}')");

最新更新