如何将System.Type解析为System.Data.DbType?

在System命名空间中查找基类库类型的System.Data.DbType枚举值的最佳方法是什么?

常见的方法是使用类型映射,显式映射所有支持的类型( 不同的连接器/提供程序支持不同的类型 )。 这是Dapper的类型映射:

 typeMap = new Dictionary(); 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; 

要获得相关的DbType,您需要做的就是:

 var type = typeMap[typeof(string)]; // returns DbType.String 

您可以使用System.Web.UI.WebControls.Parameter类中的方法ConvertTypeCodeToDbTypeTypeCode转换为DbType : Parameter.ConvertTypeCodeToDbType方法 。 要获取TypeCode,您可以使用方法Type.GetTypeCode(Type type)

您查看文档 – SQL Server数据类型映射(ADO.NET) 。

还记录了其他提供商的映射。

这些为您提供了编写转换器的足够信息。

我不知道任何自动逻辑,您应该自己进行映射,因为它们是不同的类型,.NET Framework不能单独为您执行此操作。

在这里看到整个映射表: SQL Server数据类型映射(ADO.NET)你可以想象,对于Oracle,MySQL,sqLite和其他引擎,也可能有类似的表,这取决于.NET数据提供者/连接