.net - 将 SqlDbType 转换为 .net 类型
问题描述
有很多示例如何从标准 :net 类或实例转换 SqlDbType 枚举。我在互联网上没有找到任何落后的解决方案。它似乎不太常见,但应该是(我认为)一种更简单的方法,然后只是一个覆盖所有 31 个枚举成员的巨大开关盒。
有谁知道如何SqlDbType
以更好的方式转换为 .net 类型,然后切换所有可能的枚举值?
感谢蒂姆·施梅尔特的评论。似乎那是唯一的解决方案。
解决方案
.NET 不包含此映射绝对很奇怪(而且 SqlTypes 也有点乱),但“更好的方法”是一个以枚举为键的字典。如果您的项目仅支持可用列类型的子集,这也可以轻松测试有效性。我维护一个处理动态定义的 SQL 表布局的项目。这样我的图书馆消费者只需要考虑SqlDbType
而不用担心内部DataColumn
映射。
internal static readonly Dictionary<SqlDbType, Type> equivalentSystemType = new Dictionary<SqlDbType, Type>
{
{ SqlDbType.BigInt, typeof(long) },
{ SqlDbType.Binary, typeof(byte[]) },
{ SqlDbType.Bit, typeof(bool) },
{ SqlDbType.Char, typeof(string) },
{ SqlDbType.Date, typeof(DateTime) },
{ SqlDbType.DateTime, typeof(DateTime) },
{ SqlDbType.DateTime2, typeof(DateTime) }, // SQL2008+
{ SqlDbType.DateTimeOffset, typeof(DateTimeOffset) }, // SQL2008+
{ SqlDbType.Decimal, typeof(decimal) },
{ SqlDbType.Float, typeof(double) },
{ SqlDbType.Image, typeof(byte[]) },
{ SqlDbType.Int, typeof(int) },
{ SqlDbType.Money, typeof(decimal) },
{ SqlDbType.NChar, typeof(string) },
{ SqlDbType.NVarChar, typeof(string) },
{ SqlDbType.Real, typeof(float) },
{ SqlDbType.SmallDateTime, typeof(DateTime) },
{ SqlDbType.SmallInt, typeof(short) },
{ SqlDbType.SmallMoney, typeof(decimal) },
{ SqlDbType.Time, typeof(TimeSpan) }, // SQL2008+
{ SqlDbType.TinyInt, typeof(byte) },
{ SqlDbType.UniqueIdentifier, typeof(Guid) },
{ SqlDbType.VarBinary, typeof(byte[]) },
{ SqlDbType.VarChar, typeof(string) },
{ SqlDbType.Xml, typeof(SqlXml) }
// omitted special types: timestamp
// omitted deprecated types: ntext, text
// not supported by enum: numeric, FILESTREAM, rowversion, sql_variant
};
推荐阅读
- php - 我已经创建了一个 html 提交按钮并与 php 代码连接,但是,在选择之后我该如何返回我的 html 页面?
- ssl - 替换 SSL 证书后,启动 WAMP 时出现 WAMP 错误图标为橙色
- android - 如何在 Retrofit 2 中为请求使用注释?
- ruby-on-rails - 使用 capistrano 部署到 AWS 时,Rails 服务器不断崩溃而没有任何日志
- mongodb - $group 与 $lookup
- nestjs - 神秘的`@Module() 装饰器中的“模块”键已弃用`
- list - React Native 中的长列表:分页还是无限列表?
- python - 通过 rdd.pipe 重定向日志在 Spark Scala 中使用 Python
- angular6 - 无法解析 'rxjs/add/operator/do'
- node.js - 无法从我在 heroku 上的 nodejs 应用程序将日志保存到服务器