我正在努力阅读一组结果,但遇到数据库可能返回类型的可空版本的问题,例如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);
}
}
}
答案 0 :(得分:5)
请使用以下功能:
public Type GetNullableTypeFrom(Type type)
{
if (!type.IsValueType || type.IsGenericType)
return type;
var nullableType = typeof(Nullable<>).MakeGenericType(type);
return nullableType;
}
如果源类型不是,则会将您的类型转换为可为空的类型,否则只需将其保留原样。
if (allowNulls)
{
type = GetNullableTypeFrom(type);
}
答案 1 :(得分:1)
typeof(Nullable<>).MakeGenericType(type);
是获取可空类型的关键
for (int i = 0; i < schema.Rows.Count; i++)
{
var name = (string)schema.Rows[i]["ColumnName"];
var allowNulls = (bool)schema.Rows[i]["AllowDBNull"];
Type type = (Type)schema.Rows[i]["DataType"];
// Add a condition to check value type. e.g. string should be non-nullable
// SQL data type should be all non-generic, skip check
if (allowNulls && type.IsValueType)
{
type = typeof(Nullable<>).MakeGenericType(type);
}
}