1
EnumType = reader["EnumTypeId"] == DBNull.Value ? EnumType.None : (EnumType)(int)reader["EnumTypeId"];

I thought if reader["EnumTypeId"] is null, it should assign the EnumType.None value, but it is still trying to cast the null value to an int which is obviously causing an exception.

I tried the following and it did not work either:

EnumType = reader["EnumTypeId"] == null ? EnumType.None : (EnumType)(int)reader["EnumTypeId"];

Instead of using Enums, I went ahead and decided to use a nullable int, so now my code is slightly different, but it still does not work with DBNull.Value, null, or GetOrdinal...

intType= reader["intType"] == DBNull.Value ? null : (int?)reader["intType"];

Also, why do I have to do a (int?) cast instead of just a (int) cast?

Xaisoft
  • 45,655
  • 87
  • 279
  • 432

2 Answers2

2

Don't use DBNull, just use plain old null.

EnumType = reader["EnumTypeId"] == null ? EnumType.None : (EnumType)(int)reader["EnumTypeId"];

Edit

The issue could be that the database type of EnumTypeId isn't an int/Int32. If so, then reading as a string and then parsing should fix the problem.

EnumType? enumVal = null;
if (reader["EnumTypeId"] != null)
{
    int intVal;
    enumVal = (int.TryParse(reader["EnumTypeId"].ToString(), out intVal)) ? (EnumType)intVal : null;
}
EnumType =  ? EnumType.None : (EnumType)(int)reader["EnumTypeId"];
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
  • What is the difference between DBNull and null? – Xaisoft Sep 25 '12 at 05:20
  • 1
    See: http://stackoverflow.com/questions/4958379/what-is-the-difference-between-null-and-system-dbnull-value – Emond Sep 25 '12 at 05:27
  • I can't see a straight answer in the documentation (http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx), but I remember that using `null` "works". Maybe Cuong Le's answer is more correct, I really don't know. – McGarnagle Sep 25 '12 at 05:32
  • I decided to try just using an int instead of an enum, but still getting errors. Take a look at my updated post. – Xaisoft Sep 25 '12 at 14:41
  • 1
    It was totally something else, both DBNull.Value and null work, I just forgot to add the column to the stored proc that brings back the data. It totally slipped my mind. – Xaisoft Sep 25 '12 at 18:05
1

Another way you can use is IsDBNull method:

int index = reader.GetOrdinal("EnumTypeId");
EnumType = reader.IsDBNull(index) ? EnumType.None : 
                                    (EnumType)reader.GetInt32(index);
cuongle
  • 74,024
  • 28
  • 151
  • 206