Lil*_*sey 8 c# dbnull null-coalescing-operator
我已将Class Person属性Birthday定义为可为空的DateTime?,那么为什么空融合运算符不应该在以下示例中起作用?
cmd.Parameters.Add(new SqlParameter("@Birthday",
SqlDbType.SmallDateTime)).Value =
person.Birthday ?? DBNull.Value;
Run Code Online (Sandbox Code Playgroud)
我得到的编译器错误是"操作员'??' 不能应用于'System.DateTime?'类型的操作数 和'System.DBNull'"
以下也出现了编译错误:
cmd.Parameters.Add(new SqlParameter("@Birthday",
SqlDbType.SmallDateTime)).Value =
(person.Birthday == null) ? person.Birthday:DBNull.Value;
Run Code Online (Sandbox Code Playgroud)
我按照Refactor的建议添加了一个强制转换为(对象),然后编译,但是没有正常工作,并且在两种情况下,值都存储在sqlserver db中为null.
SqlDbType.SmallDateTime)).Value =
person.Birthday ?? (object)DBNull.Value;
Run Code Online (Sandbox Code Playgroud)
有人能解释一下这里发生了什么吗?
我需要使用以下笨拙的代码:
if (person.Birthday == null)
cmd.Parameters.Add("@Birthday", SqlDbType.SmallDateTime).Value
= DBNull.Value;
else cmd.Parameters.Add("@Birthday", SqlDbType.SmallDateTime).Value =
person.Birthday;
Run Code Online (Sandbox Code Playgroud)
Dav*_*wns 22
问题是,DateTime?并且DBNull.Value不是同一类型,因此您不能对它们使用空合并运算符.
在您的情况下,您可以person.Birthday ?? (object)DBNull.Value将类型的值传递object给Add()
我更喜欢在执行查询之前迭代参数,根据需要将所有 null 实例更改为 DBNull,例如:
foreach (IDataParameter param in cmd.Parameters)
if (param.Value == null)
param.Value = DBNull.Value;
Run Code Online (Sandbox Code Playgroud)
这让我可以按原样保留空值,然后简单地将它们全部交换掉。
| 归档时间: |
|
| 查看次数: |
4263 次 |
| 最近记录: |