Handling a DateTime DBNull

前端 未结 6 1865
广开言路
广开言路 2021-01-18 00:32

I have seen many, many versions of this on SO, but none of them seem to quite work for my needs.

My data comes from a vendor database that allows null for DateTime

6条回答
  •  无人共我
    2021-01-18 00:53

    I have found that the easiest way to handle this is to cast the field as your data type using the "as" keyword. This works great for database fields that can be null, and is nice and simple.

    Here is more detail on this: Direct casting vs 'as' operator?

    Example:

        IDataRecord record = FromSomeSqlQuerySource;
        string nullableString;
        DateTime? nullableDateTime;
    
        nullableString = record["StringFromRecord"] as string;
        nullableDateTime = record["DateTimeFromRecord"] as DateTime?;
    

提交回复
热议问题