Can I cast from DBNull to a Nullable Bool in one line?

后端 未结 5 809
南笙
南笙 2021-02-19 04:37

I have a database query which will either return NULL or a boolean (bit) value.

I wish to store this value in a variable of type Nullable<

相关标签:
5条回答
  • 2021-02-19 04:55

    assuming you have a datareader dr:

    bool? tmp = Convert.IsDBNull(dr["dbnullValue"]) ? null: (bool?) dr["dbnullValue"];
    

    ---ADDED----

    or maybe you can use the ?? if you don't have to check for DBNull but i'm not sure compiler will like this (i cannot test it now)

    bool? tmp = dr["dbnullValue"] ?? (bool?) dr["dbnullValue"];
    
    0 讨论(0)
  • 2021-02-19 05:00

    You could write value as bool?.
    This will return null if value is not of type bool.

    Note that this is somewhat inefficient.

    0 讨论(0)
  • 2021-02-19 05:00

    I use extension methods for this issue.

    var isRestricted = dataRecord.GetNullableValue<bool>("IsRestricted");
    

    There is code of GetNullableValue method:

        public static Nullable<TValue> GetNullableValue<TValue>(
            this IDataRecord record, 
            string name) where TValue : struct
        {
            return record.GetValue<TValue, Nullable<TValue>>(name);
        }
    

    And there is also a simple code for GetValue method:

            private static TResult GetValue<TValue, TResult>(
            this IDataRecord record,
            string name)
        {
            var result = record[name];
            return !result.Equals(DBNull.Value) ? (TResult)result : default(TResult);
        }
    
    0 讨论(0)
  • 2021-02-19 05:02

    You can just do the following

    bool? myNullableBoolean = SqlConvert.ToType<bool?>(reader["myNullableBooleanColumn"]);

    0 讨论(0)
  • 2021-02-19 05:05
     while (reader.Read()) {
        bool? IsRestricted = (reader.IsDBNull(reader.GetOrdinal("IsRestricted"))) ? (null) : ((bool)reader.GetOrdinal("IsRestricted")));
     }
    
    0 讨论(0)
提交回复
热议问题