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

后端 未结 5 808
南笙
南笙 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 05:00

    I use extension methods for this issue.

    var isRestricted = dataRecord.GetNullableValue("IsRestricted");
    

    There is code of GetNullableValue method:

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

    And there is also a simple code for GetValue method:

            private static TResult GetValue(
            this IDataRecord record,
            string name)
        {
            var result = record[name];
            return !result.Equals(DBNull.Value) ? (TResult)result : default(TResult);
        }
    

提交回复
热议问题