How can i identify whether the value from the database is null or not in .Net 2.0?
I am fetching the data from the database and populate it into the domain object.Lets say
public class A
{
int? ai;
public int? AI
{
get { value = ai;}
Set { ai = value; }
}
}
so i am creating the domain object in the main class.
class TestClass
{
static void Main(string[] args)
{
class A objData = new A();
// here some logic for creating connection to the database and calling the datareader to fetch the //data.
int temp =(int) objDataReader["aiDAta"];
objData.ai = temp == null? 0: temp;
func(objData);
}
}
public void func(A objData)
{
// Here i want to display the value of objData.ai only if its database value is not null.since i was //already assigned 0,if the value from the database is null...how can i able to identify whether the value //from the database is null or not? also,In database "aiDAta" will have the value range from 0 - 99.
}
}
Here i want to display the value of objData.ai only if its database value is not null.since i was already assigned 0,if the value from the database is null...how can i able to identify whether the value from the database is null or not? also,In da开发者_开发百科tabase "aiDAta" will have the value range from 0 - 99.
Compare objData.ai to
DBNull.value
instead of NULL
or
check
IsDBNull(objData.ai)
or
public Int32 TryCastInteger32(object value)
{
if (value != null && !Information.IsDBNull(value)) {
Int32 retVal = default(Int32);
if (Int32.TryParse(value.ToString(), out retVal)) {
return retVal;
}
}
return 0;
}
If your casting to a Nullable checked the HasValue property. It will be true only is the value type is not null.
Usually null DB fields are returned as System.DbNull in which case the following cast will fail:
int temp =(int) objDataReader["aiDAta"];
You can use DBDataReader's IsNull method to check for a null value before using it
alternatively you could also just let the database validate if the value is null or not by creating an oracle function and passing the value you want it to evaluate:
CREATE OR REPLACE
FUNCTION isNull(
i_value IN VARCHAR2)
RETURN NUMBER
IS
BEGIN
IF i_value IS NOT NULL THEN
RETURN 1;
ELSE
RETURN 0;
END IF;
END;
/
精彩评论