我有一个带有类型列的 SQL 表,nvarchar(20)并希望使用SqlDataReader. 看起来这样做的唯一方法是使用GetSqlChars()后跟ToSqlString():
String result = reader.GetSqlChars(index).ToSqlString().Value
问题是,如果存储的值恰好为空(这对我的情况有效)我得到
[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;
这可行,但需要大量额外的代码,而且看起来很不优雅。
有没有更优雅的方式来达到同样的效果?