简体   繁体   English

C#6中的null和字符串插值

[英]null and string interpolation in C# 6

I am using new C# 6.0 features String Interpolation for generating SQL statements. 我正在使用新的C#6.0功能“字符串插值”来生成SQL语句。

$@"INSERT INTO [dbo].[TableName]([Column1], [Column2]) Values({item.property1}, {item.property2})";

If properties are null then generated SQL is the following 如果属性为null,则生成的SQL如下

INSERT INTO [dbo].[TableName]([Column1], [Column2]) Values(,)

And this cause an error. 这会导致错误。 (Incorrect SQL). (错误的SQL)。
I need Null instead of empty spaces. 我需要Null而不是空白。 Can i somehow achieve this ? 我能以某种方式实现这一目标吗?

{Convert.ToString(item.property1) ?? "NULL"} {Convert.ToString(item.property1) ?? "NULL"} should do it. {Convert.ToString(item.property1) ?? "NULL"}应该做到这一点。 This is still broken, because you need very specific formatting for the SQL to come out right. 这仍然是无效的,因为您需要非常特定的格式才能正确显示SQL。 You can solve the formatting yourself. 您可以自己解决格式问题。

The usual SQL injection disclaimers have been given in the comments already. 注释中已经给出了通常的SQL注入免责声明。 This approach is unsalvagable. 这种方法是不可挽回的。 You need to throw this away. 您需要扔掉它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM