How to parse Nullable from a SqlDataRead

2019-06-16 03:25发布

问题:

The DateTime.TryParse method takes a DateTime as an argument, not a DateTime? ?

Right now I have the following code:

if(!DateTime.TryParse(reader["Placed"].ToString(), out _placed)){
    throw new Exception("Order's placed datetime could not be parsed.");
}

where _placed is of type

Nullable<DateTime> _placed = null;

What's a way around that?

回答1:

How about this instead:

int x = reader.GetOrdinal("Placed");

if(!reader.IsDBNull(x))
    _placed = reader.GetDateTime(x);


回答2:

Just a combination of top answer and top comment. Thanks @Dylan-Meador and @LukeH.
(Ed. Note: For the long tail I think this version will save plenty of human time.)

int x = reader.GetOrdinal("Placed");
DateTime? _placed = reader.IsDBNull(x) ? (DateTime?)null : reader.GetDateTime(x);


回答3:

And here is @yzorg 's answer turned into a reusable extension method

public static class SqlDataReaderExtensions
{
    public static DateTime? GetNullableDateTime(this SqlDataReader reader, string fieldName)
    {
        int x = reader.GetOrdinal(fieldName);
        return reader.IsDBNull(x) ? (DateTime?) null : reader.GetDateTime(x);
    }
}


回答4:

DateTime? _placed  = null;
DateTime d2;
bool isDate = DateTime.TryParse(reader["Placed"].ToString(), out d2);
if (isDate) _placed  = d2;


回答5:

Use the IsDBNull method of the reader to determine if the value is null prior to trying to parse a date out of it.



回答6:

It's normal. The out argument is not set if the parse fail. So if the type of the wargument were Nullable it would have been a redudant information.



标签: c# tsql