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

标签 c# .net ado.net

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

最佳答案

一种常见的方法是使用类型映射,明确映射所有支持的类型(不同的连接器/提供程序支持不同的类型)。这是 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;

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

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

关于c# - 如何将 System.Type 解析为 System.Data.DbType?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7952142/

相关文章:

c# - 更改数组大小

c# - 如何实现一对多关系

c# - 如何将行插入到 Excel 工作表内的表对象?

c# - 修改语法树,然后得到更新的语义模型

c# - 从链接下载文件

c# - 如何使用 C# 代码(不是 python)将静态类(或静态方法)导入 IronPython(或 DLR)?

.net - 在 MVC 5 Membership 中更改密码长度

.net - 获取模式匹配中可区分联合的大小写标识符

.net - 无法使用 Syste.Data.SQLite.dll x86 运行 mspec.exe,但它可以在 R# MSpec 运行程序中运行

c# - 注入(inject)存储库上的 IDisposable