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

混江龙づ霸主 提交于 2020-01-22 17:20:12

问题


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<bool> in C#.

I can't seem to find an acceptable mix of explict casts and conversions that do this in a simple way without Exceptions being thrown.

Can it be done in one readable line?

EDIT: Code as requested

private Nullable<bool> IsRestricted;
...//data access
IsRestricted = (bool?)DataBinder.GetPropertyValue(dataObj, "IsRestricted");

or perhaps

IsRestricted = (bool?)(bool)DataBinder.GetPropertyValue(dataObj, "IsRestricted");

回答1:


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"];



回答2:


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

Note that this is somewhat inefficient.




回答3:


 while (reader.Read()) {
    bool? IsRestricted = (reader.IsDBNull(reader.GetOrdinal("IsRestricted"))) ? (null) : ((bool)reader.GetOrdinal("IsRestricted")));
 }



回答4:


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);
    }



回答5:


You can just do the following

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



来源:https://stackoverflow.com/questions/14609921/can-i-cast-from-dbnull-to-a-nullable-bool-in-one-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!