我有一个SQL表,其列的类型为nvarchar(20),并希望使用SqlDataReader读取该列.看起来这样做的唯一方法是使用GetSqlChars()后跟ToSqlString():
String result = reader.GetSqlChars(index).ToSqlString().Value
问题是,如果存储的值恰好为null(并且这对我的情况有效),我得到
[SqlNullValueException: Data is Null. This method or property cannot be called on Null values.] System.Data.SqlTypes.SqlString.get_Value() +3212527
所以我必须首先检查ToSqlString()返回的值在IsNull()中返回的内容:
SqlString asSqlString = reader.GetSqlChars(index).ToSqlString(); String result = asSqlString.IsNull() ? null : asSqlString.Value;
它有效,但需要大量额外的代码,看起来真的很不优雅.
是否有更优雅的方式来达到同样的效果?
也许:var value = reader.IsDBNull(index) ? null : reader.GetString(index);
甚至更短:
var value = reader[index] as string;
查看更多关于c# – 如果允许空值,如何将nvarchar(x)读入String?的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did69334