首页 > 解决方案 > 将 SqlDbType 转换为 .net 类型

问题描述

有很多示例如何从标准 :net 类或实例转换 SqlDbType 枚举。我在互联网上没有找到任何落后的解决方案。它似乎不太常见,但应该是(我认为)一种更简单的方法,然后只是一个覆盖所有 31 个枚举成员的巨大开关盒。

有谁知道如何SqlDbType以更好的方式转换为 .net 类型,然后切换所有可能的枚举值?

感谢蒂姆·施梅尔特的评论。似乎那是唯一的解决方案。

标签: .netado.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
};

推荐阅读