简体   繁体   中英

Check Int32 is Null

I have a SQL Server stored procedure that I can run (and I get output from it), but a few off the columns come back as null.

The code I am using in my controller is :

Int32 Output7 = SPOutput.GetInt32(SPOutput.GetOrdinal("ptransient"));
ViewBag.Output7 = Output7;

But when I run the code, I get

System.Data.SqlTypes.SqlNullValueException: 'Data is Null. This method or property cannot be called on Null values.'

from the "int32" line.

I have tried Int32? Output7 Int32? Output7 etc, but I get the same error.

I've tried putting in a if Loop to check if Output7.HasValue , but the exception occurs prior to this.

I think I need a way of check the value BEFORE I assign it to the Int32 Output7 variable , but am stuck as to how (still a lower level noobie @ MVC).

I have googled and look thought SO (prob badly), but could not find a solution. Could someone point out what I should be doing ?

Thanks

Presumably SPOutput.GetInt32() is trying to get an int , not an int? . Regardless of what you're assigning the result of that operation to, internally the operation itself is trying to produce an int . And you can't produce an int from a null value.

Check if the database value is null before trying. Perhaps something similar to this:

int? output7 = null;
if (SPOutput.GetValue(SPOutput.GetOrdinal("ptransient")) != DBNull.Value)
    output7 = SPOutput.GetInt32(SPOutput.GetOrdinal("ptransient"));

That way the value defaults to null , but is assigned to the integer value from the data if there is an integer value in the data.

(Note that this assumes your code is using the same data access technology that uses DBNull.Value , generally plain ADO.NET.)

Did you check SPOutput or SPOutput.GetOrdinal("ptransient") is null, if not, try:

Int32 Output7;
if (SPOutput!= System.DBNull.Value && SPOutput.GetOrdinal("ptransient")!= System.DBNull.Value)
{
  Output7 = SPOutput.GetInt32(SPOutput.GetOrdinal("ptransient"));
  ViewBag.Output7 = Output7;
}

The easiest way to solve this is don't use GetInt32 at all and just get the object version of the value then cast with a as , this will pass through int values and DbNull values just become normal null

Int32? Output7 = SPOutput["ptransient"] as Int32?;
ViewBag.Output7 = Output7;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM