Samir Samir - 1 year ago 83
ASP.NET (C#) Question

int? not working for db nulls

So I thought the point of (int?) was to take an int or null if the db has null. However I am getting an error

Additional information: Specified cast is not valid.

is the one giving the error because it is NULL in the database. It is (int?) so it should be able to take in null values right? Isn't that the point of (int?)? If not, what is the cleanest solution to allow nulls because there are actually a lot more nullable ints I have to get from the db.

Here is my code:

public int? VehicleClassID { get; set; }
public int? VehicleGroupID { get; set; }

public void getVehicleModelDetails ()
DataSet retVal = new DataSet();
SqlConnection sqlConn = (SqlConnection)_context.Database.Connection;
SqlCommand cmdReport = new SqlCommand("storedProc", sqlConn);
SqlDataAdapter daReport = new SqlDataAdapter(cmdReport);
using (cmdReport)
cmdReport.CommandType = CommandType.StoredProcedure;

// Set buyer vehicle details
var row = retVal.Tables[0].Rows[0];
VehicleClassID = (int?)row["VehicleClassID"];
VehicleGroupID = (int?)row["VehicleGroupID"];

FYI: I am using EF6, but the stored procedure returns custom data so I resorted to this.

Answer Source

As per my knowledge, Field extension method supports nullable types. So, below line should work as a charm:

VehicleClassID = row.Field<int?>("VehicleClassID");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download