【发布时间】:2015-09-24 07:56:00
【问题描述】:
我正在阅读一组结果,但遇到了数据库可能返回一个类型的可为空版本的问题,例如 double 或 int。
我想知道是否可以使用来自阅读器的架构信息将类型定义转换为可为空的版本。比如double?或者int??
抛开所有 SQL 的东西,一般有没有办法进行这种类型转换?从Type 对象到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);
}
}
}
【问题讨论】:
-
关闭,但不完全——我正在尝试从提供的架构中创建准确的类型信息。架构返回
double作为类型,而真正的double?会更准确。
标签: c# nullable sqlcommand