I am working on reading a set of results, but running into issues where a database may return a nullable version of a type, such as a double
or int
.
I am wondering if it's possible to use the schema information from the reader to convert the type definition to a nullable version. such as double?
or int?
?
All the SQL stuff aside, is there a way to do this kind of type conversion in general? From a Type
object to a Nullable<Type>
.
using (SqlConnection connection = new SqlConnection("... connection string here ..."))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = ".... some sql here ....";
var results = new DataTable(schema.TableName);
using (var reader = await command.ExecuteReaderAsync())
using (var schema = reader.GetSchemaTable())
{
for (int i = 0; i < schema.Rows.Count; i++)
{
var name = (string)schema.Rows[i]["ColumnName"];
var type = (Type)schema.Rows[i]["DataType"];
var allowNulls = (bool)schema.Rows[i]["AllowDBNull"];
if (allowNulls)
{
// --- How do we turn `type` into a nullable version?
// Int32 => Nullable<Int32>
// Double => Nullable<Double>
// ... etc ...
}
var column = new DataColumn(name, type);
results.Columns.Add(column);
}
}
}