我可以在一行中从DBNull转换为Nullable Bool吗?
我有一个数据库查询,它将返回NULL
或布尔(位)值。
我希望将此值存储在C#中Nullable
类型的变量中。
我似乎无法找到一个可接受的explict强制转换和转换组合,以简单的方式执行此操作,而不会抛出exception。
可以用一条可读行完成吗?
编辑:代码请求
private Nullable IsRestricted; ...//data access IsRestricted = (bool?)DataBinder.GetPropertyValue(dataObj, "IsRestricted");
也许
IsRestricted = (bool?)(bool)DataBinder.GetPropertyValue(dataObj, "IsRestricted");
假设你有一个datareader博士:
bool? tmp = Convert.IsDBNull(dr["dbnullValue"]) ? null: (bool?) dr["dbnullValue"];
– -添加 – –
或者你可以使用?? 如果您不必检查DBNull但我不确定编译器是否会喜欢这个(我现在无法测试)
bool? tmp = dr["dbnullValue"] ?? (bool?) dr["dbnullValue"];
你可以把value as bool?
。
如果value
不是bool
类型,则返回null
。
请注意, 这有点低效 。
while (reader.Read()) { bool? IsRestricted = (reader.IsDBNull(reader.GetOrdinal("IsRestricted"))) ? (null) : ((bool)reader.GetOrdinal("IsRestricted"))); }
我使用扩展方法来解决这个问题。
var isRestricted = dataRecord.GetNullableValue("IsRestricted");
有GetNullableValue方法的代码:
public static Nullable GetNullableValue ( this IDataRecord record, string name) where TValue : struct { return record.GetValue>(name); }
还有一个简单的GetValue方法代码:
private static TResult GetValue( this IDataRecord record, string name) { var result = record[name]; return !result.Equals(DBNull.Value) ? (TResult)result : default(TResult); }