0

I have the following function in C#, that I want to pass a MySQL DataReader value/object.

If the value of the object passed is a DBNull I need to handle it and return a Null value of that data type e.g null int.

Otherwise I want to convert the returned value like Convert.ToInt32(value) or similar. My function is;

public static T ConvertFromDB<T>(object value)
{
     return value == DBNull.Value ? default(T) : (T)value;
}

I can call the function like

int MyInt = ConvertFromDB(oRes["FieldName"]);

However in this case the MySQLDataReader result for oRes["FieldName"] is a DBNull, which causes a exception.

Can anyone offer any help on this ? I am using strongly typed columns, but the problem I have is if the DB value is DBNull, I need to return null of that data type e.g (int)null

4

1 回答 1

1

Maybe you're looking for Convert.ChangeType()?

return value == DBNull.Value ? default(T) : (T) Convert.ChangeType(value, typeof(T));

Note that you're going to have to deal with exceptions when the conversion fails, which makes extension methods like this suspect.

That said, if you're reading strongly typed columns, they should already be in the format you want. Why not just use SqlDataReader.GetInt32() (or similar)? If it's because you want to refer to your DB columns by name using the SqlDataReader's index operator, maybe you'd be better off with a set of extension methods that add overloads and call GetOrdinal() within them instead. Some might argue that this is indicative of other code smells.

于 2013-11-01T15:35:13.807 回答