从IDataReader获取值的空安全方法 [英] Null safe way to get values from an IDataReader
问题描述
(LocalVariable)ABC.string(Name)=(Idatareader)datareader.GetString(0);
(LocalVariable)ABC.string(Name)= (Idatareader)datareader.GetString(0);
此名称值来自数据库. 如果此名称值在读取时抛出异常,则为空?
this name value is coming from database.. what happening here is if this name value is null while reading it's throwing an exception?
我在这里手动执行一些if条件.我不想编写手动条件来检查我所有的变量.
I am manually doing some if condition here. I don't want to write a manual condition to check all my variables..
我现在正在做这样的事情.
I am doing something like this now..
string abc = (Idatareader)datareader.GetValue(0);
if(abc = null)
//assiging null
else
assiging abc value
是否可以为它编写扩展方法? 谢谢
is there something like can we write extension method for this? thanks
推荐答案
以下是几种扩展方法,它们很好地总结了您从数据读取器中检索强类型值的所有问题.如果值为DbNull,则将返回该类型的默认值.如果string
是一个类,则将返回null
.如果该字段是int
,则将返回0
.此外,如果您期望int?
,例如从可为null的int字段中返回,则将返回null
.
Here is a couple extension methods that will nicely wrap up all of your concerns around retrieving strongly typed values from a data reader. If the value is DbNull the default of the type will be returned. In the case of string
which is a class, a null
will be returned. If the field was int
, then 0
would be returned. Additionally, if you are expecting an int?
, say from an nullable int field, null
would be returned.
Kumar案件的具体用法:
Specific Usage for Kumar's case:
string abc = datareader.GetValueOrDefault<string>(0);
一般用法
var name = GetValueOrDefault<string>(reader, "Name");
或
var name = reader.GetValueOrDefault<string>("Name");
或
var name = reader.GetValueOrDefault<string>(0);
扩展名
public static class NullSafeGetter
{
public static T GetValueOrDefault<T>(this IDataRecord row, string fieldName)
{
int ordinal = row.GetOrdinal(fieldName);
return row.GetValueOrDefault<T>(ordinal);
}
public static T GetValueOrDefault<T>(this IDataRecord row, int ordinal)
{
return (T)(row.IsDBNull(ordinal) ? default(T) : row.GetValue(ordinal));
}
}
来自 http://skysanders .net/subtext/archive/2010/03/02/generic-nullsafe-idatarecord-field-getter.aspx
这篇关于从IDataReader获取值的空安全方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!