2

I have a simple value object which I populate with data from an IDataReader (could be the result of a query to either an Oracle or MS SQL database). The factory method for this object looks something like the following:

internal static SomeClass CreateFromDataReader(IDataReader data)
{
    string message = data.GetString(0);
    short id = data.GetInt16(1);
    DateTime dateStamp = data.GetDateTime(2);
    return new SomeClass(message, id, dateStamp);
}

I then ran into a problem which is related to the difference in the data type that the Oracle and MS SQL databases use for that particular column: in Oracle that data type is number while for MS SQL the data type used is smallint.

Now, while I could 'fix' this problem by doing something like the following:

short id = Convert.ToInt16(data.GetValue(1));

is there a better or more elegant way of doing this?

jpoh
  • 4,536
  • 4
  • 35
  • 60

2 Answers2

1

I don't know how ORMs take care of such a scenario.

However, you should use a type that can accomodate both (all) cases for such a field.
I looked at this table & it seems decimal is the appropriate .net data type you could use.

shahkalpesh
  • 33,172
  • 3
  • 63
  • 88
0

Your idea is the right way. Perhaps even shorter:

short id = Convert.ToInt16(data[1]); //8 characters less

Or make extension method.

public static short ToShort(this IDataReader r, int index)
{
    return Convert.ToInt16(r[index]);
}

Now you can:

short id = data.ToShort(1); //18 characters less

:)

nawfal
  • 70,104
  • 56
  • 326
  • 368