System.Data.DbType
在System命名空间中查找基类库类型的枚举值的最佳方法是什么?
ale*_*exn 70
常见的方法是使用类型映射,显式映射所有支持的类型(不同的连接器/提供程序支持不同的类型).这是Dapper的类型映射:
typeMap = new Dictionary<Type, DbType>();
typeMap[typeof(byte)] = DbType.Byte;
typeMap[typeof(sbyte)] = DbType.SByte;
typeMap[typeof(short)] = DbType.Int16;
typeMap[typeof(ushort)] = DbType.UInt16;
typeMap[typeof(int)] = DbType.Int32;
typeMap[typeof(uint)] = DbType.UInt32;
typeMap[typeof(long)] = DbType.Int64;
typeMap[typeof(ulong)] = DbType.UInt64;
typeMap[typeof(float)] = DbType.Single;
typeMap[typeof(double)] = DbType.Double;
typeMap[typeof(decimal)] = DbType.Decimal;
typeMap[typeof(bool)] = DbType.Boolean;
typeMap[typeof(string)] = DbType.String;
typeMap[typeof(char)] = DbType.StringFixedLength;
typeMap[typeof(Guid)] = DbType.Guid;
typeMap[typeof(DateTime)] = DbType.DateTime;
typeMap[typeof(DateTimeOffset)] = DbType.DateTimeOffset;
typeMap[typeof(byte[])] = DbType.Binary;
typeMap[typeof(byte?)] = DbType.Byte;
typeMap[typeof(sbyte?)] = DbType.SByte;
typeMap[typeof(short?)] = DbType.Int16;
typeMap[typeof(ushort?)] = DbType.UInt16;
typeMap[typeof(int?)] = DbType.Int32;
typeMap[typeof(uint?)] = DbType.UInt32;
typeMap[typeof(long?)] = DbType.Int64;
typeMap[typeof(ulong?)] = DbType.UInt64;
typeMap[typeof(float?)] = DbType.Single;
typeMap[typeof(double?)] = DbType.Double;
typeMap[typeof(decimal?)] = DbType.Decimal;
typeMap[typeof(bool?)] = DbType.Boolean;
typeMap[typeof(char?)] = DbType.StringFixedLength;
typeMap[typeof(Guid?)] = DbType.Guid;
typeMap[typeof(DateTime?)] = DbType.DateTime;
typeMap[typeof(DateTimeOffset?)] = DbType.DateTimeOffset;
typeMap[typeof(System.Data.Linq.Binary)] = DbType.Binary;
Run Code Online (Sandbox Code Playgroud)
要获得相关的DbType,您需要做的就是:
var type = typeMap[typeof(string)]; // returns DbType.String
Run Code Online (Sandbox Code Playgroud)
小智 12
您可以转换TypeCode
到DbType
使用方法ConvertTypeCodeToDbType
的System.Web.UI.WebControls.Parameter
类:Parameter.ConvertTypeCodeToDbType方法.要获取TypeCode,您可以使用方法Type.GetTypeCode(Type type)
.
我知道这是一个已经回答的老问题,但是使用更简单的方法SqlParameter
,它已经实现了这个逻辑。这是特定于SqlServer的,但是Postgre、MySql .. 等的提供者都有相应的实现。
这是一个完整的函数,它处理不可为空、可为空的基本类型、小数和字符串
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;
}
Run Code Online (Sandbox Code Playgroud)
如何获取Sql参数:
对于SqlServer,根据您的 .netframework 版本,您可以SqlParamter
在System.Data、System.Data.SqlClient nuget和Microsoft.Data.SqlClient nuget中找到类型
SqlParameter的源代码:
SqlParameter的实现正在使用这段代码,它非常接近所接受的答案所建议的内容。