How to resolve System.Type to System.Data.DbType?

前端 未结 5 610
礼貌的吻别
礼貌的吻别 2020-12-04 22:20

What is the best way to find System.Data.DbType enumeration value for Base Class Library types in System namespace?

5条回答
  •  隐瞒了意图╮
    2020-12-04 22:50

    I know it is old question which is already answered, but there is easier way by using SqlParameter, which already has this logic implemented. This is specific for SqlServer, but the providers for Postgre, MySql .. etc have corresponding implementations.

    Here is a complete function which handles non-nullable, nullable primitive types, decimal and string

    public static DbType GetDbType(Type runtimeType)
    {
        var nonNullableType = Nullable.GetUnderlyingType(runtimeType);
        if (nonNullableType != null)
        {
            runtimeType = nonNullableType;
        }
    
        var templateValue = (Object)null;
        if (runtimeType.IsClass == false)
        {
            templateValue = Activator.CreateInstance(runtimeType);
        }
    
        var sqlParamter = new SqlParameter(parameterName: String.Empty, value: templateValue);
    
        return sqlParamter.DbType;
    }
    

    How to get SqlParameter:

    For SqlServer, depending on your .netframework version you can find the SqlParamter type in System.Data, System.Data.SqlClient nuget and Microsoft.Data.SqlClient nuget


    Source code for SqlParameter:

    The implementation of SqlParameter is using this piece of code which is pretty close to what the accepted answer is proposing.

提交回复
热议问题