The underlying problem you have here is that .NET cannot cast "NULL" to a string when you call reader.GetString(). To solve your problem, you must determine what you want to do if the value in the data reader is NULL and provide this in your programming code. Do you want to use an empty string? Do you want to use null? do you want an exception?
I would suggest writing an Extension Method for the DataReader class to create a new function that encapsulates your desired logic. This is an example:
public static string GetStringOrEmptyString(this IDataReader reader, int ordinal)
{
if (reader.IsDBNull(ordinal)) {
// if its DBNULL, return empty string
return "";
} else {
// otherwise return thew value as string
return reader.GetString(ordinal);
}
}
You can use this like so:
var item = new Product
{
_x1 = reader.GetStringOrEmptyString(0),
_x2 = reader.GetStringOrEmptyString(1),
_x3 = reader.GetStringOrEmptyString(2),
_x4 = reader.GetDateTime(3)
};
if (reader != nullor inside atry/catch