简体   繁体   中英

Converting `Type` to `Nullable<Type>`

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);
        }
    }
}

Please use the following function:

public Type GetNullableTypeFrom(Type type)
{
    if (!type.IsValueType || type.IsGenericType)
        return type;

    var nullableType = typeof(Nullable<>).MakeGenericType(type);

    return nullableType;
}

It will convert your type into a nullable one if the source type isn't, otherwise just leave it as it is.

if (allowNulls)
{
    type = GetNullableTypeFrom(type);
}

typeof(Nullable<>).MakeGenericType(type); is the key to get the nullable 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);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM