简体   繁体   English

DateTime和DbNull.Value

[英]DateTime and DbNull.Value

Does anyone have an idea why this works: 有谁知道为什么这样做:

if (_item.Created == DateTime.MinValue)
{
  ListSqlParam.Add(new SqlParameter("@TransactionCreated", DBNull.Value));
}
else
{
  ListSqlParam.Add(new SqlParameter("@TransactionCreated", _item.Created));
}

but not this: 但不是这个:

ListSqlParam.Add(new SqlParameter("@TransactionCreated",((_item.Created == DateTime.MinValue) ? DBNull.Value : _item.Created)));

The reason is that the conditional operator is an expression of a specific type. 原因是条件运算符是特定类型的表达式。 This specific type is infered by the compiler based on the types of the expressions in the two branches of the operator. 编译器根据运算符的两个分支中的表达式类型来推断此特定类型。
In your code, this specific type can't be infered by the compiler because DBNull.Value and _item.Created are of different and unrelated types. 在您的代码中,编译器不能使用此特定类型,因为DBNull.Value_item.Created属于不同_item.Created相关的类型。 You can't cast either one to the type of the other one. 您不能将任何一个转换为另一个的类型。

To make it work, cast at least one branch to object : 要使其工作,请将至少一个分支强制转换为object

(_item.Created == DateTime.MinValue) ? (object)DBNull.Value : _item.Created

When using the conditional operator , both types returned by the different sides of the conditional (the true and the false branches) should be the same or be implicitly convertible to each other. 使用条件运算符时条件的不同边返回的两种类型(true和false分支)应该相同或者可以隐式地相互转换。

DBNull.Value and DateTime are not such values. DBNull.ValueDateTime不是这样的值。

改为使用SqlDateTime

_item.Created == DateTime.MinValue ? SqlDateTime.Null : new SqlDateTime(_item.Created)

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

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