.NET 系统类型到 SqlDbType

.NET System Type to SqlDbType

我一直在寻找 .Net System.Type 和 SqlDbType 之间的智能转换。我发现它是以下想法:

private static SqlDbType TypeToSqlDbType(Type t)
{
    String name = t.Name;
    SqlDbType val = SqlDbType.VarChar; // default value
    try
    {
        if (name.Contains("16") || name.Contains("32") || name.Contains("64"))
            {
                name = name.Substring(0, name.Length - 2);
            }
            val = (SqlDbType)Enum.Parse(typeof(SqlDbType), name, true);
        }
        catch (Exception)
        {
            // add error handling to suit your taste
        }

        return val;
    }

上面的代码不是很好看,有点代码味,所以我写了下面的代码,幼稚,不聪明,但是有用的功能,基于https://msdn.microsoft.com/en-us/library/cc716729(v=vs.110).aspx:

   public static SqlDbType ConvertiTipo(Type giveType)
    {
       var typeMap = new Dictionary<Type, SqlDbType>();

        typeMap[typeof(string)] = SqlDbType.NVarChar;
        typeMap[typeof(char[])] = SqlDbType.NVarChar;
        typeMap[typeof(int)] = SqlDbType.Int;
        typeMap[typeof(Int32)] = SqlDbType.Int;
        typeMap[typeof(Int16)] = SqlDbType.SmallInt;
        typeMap[typeof(Int64)] = SqlDbType.BigInt;
        typeMap[typeof(Byte[])] = SqlDbType.VarBinary;
        typeMap[typeof(Boolean)] = SqlDbType.Bit;
        typeMap[typeof(DateTime)] = SqlDbType.DateTime2;
        typeMap[typeof(DateTimeOffset)] = SqlDbType.DateTimeOffset;
        typeMap[typeof(Decimal)] = SqlDbType.Decimal;
        typeMap[typeof(Double)] = SqlDbType.Float;
        typeMap[typeof(Decimal)] = SqlDbType.Money;
        typeMap[typeof(Byte)] = SqlDbType.TinyInt;
        typeMap[typeof(TimeSpan)] = SqlDbType.Time;

        return typeMap[(giveType)];
     }

有人知道如何以更干净、更好、更好的方式获得相同的结果吗?

您的方法是一个良好的开端,但正如 Ian 在评论中所说,填充该字典应该只完成 一次

这里有一个基于相同想法的 GIST,尽管它不会在相同类型集之间进行转换:https://gist.github.com/abrahamjp/858392

警告

下面有 a working example,但您需要注意这种方法确实存在一些问题。例如:

  • 对于string,如何在CharNCharVarCharNVarCharText之间选择正确的那个或 NText (甚至 Xml,也许)?
  • 对于像 byte[] 这样的 blob,您应该使用 BinaryVarBinary 还是 Image
  • 对于decimalfloatdouble,你应该选择DecimalFloatMoney、[=30=吗? ] 或 Real?
  • 对于 DateTime,您需要 DateTime2DateTimeOffsetDateTime 还是 SmallDateTime
  • 您是否使用 Nullable 类型,例如 int??那些应该最有可能给出与基础类型相同的 SqlDbType

此外,仅提供 Type 不会告诉您其他约束,例如字段大小和精度。做出正确的决定还与数据在应用程序中的使用方式以及数据在数据库中的存储方式有关。

最好的办法就是让 ORM 为您做这件事。

代码

public static class SqlHelper
{
    private static Dictionary<Type, SqlDbType> typeMap;

    // Create and populate the dictionary in the static constructor
    static SqlHelper()
    {
        typeMap = new Dictionary<Type, SqlDbType>();

        typeMap[typeof(string)]         = SqlDbType.NVarChar;
        typeMap[typeof(char[])]         = SqlDbType.NVarChar;
        typeMap[typeof(byte)]           = SqlDbType.TinyInt;
        typeMap[typeof(short)]          = SqlDbType.SmallInt;
        typeMap[typeof(int)]            = SqlDbType.Int;
        typeMap[typeof(long)]           = SqlDbType.BigInt;
        typeMap[typeof(byte[])]         = SqlDbType.Image;
        typeMap[typeof(bool)]           = SqlDbType.Bit;
        typeMap[typeof(DateTime)]       = SqlDbType.DateTime2;
        typeMap[typeof(DateTimeOffset)] = SqlDbType.DateTimeOffset;
        typeMap[typeof(decimal)]        = SqlDbType.Money;
        typeMap[typeof(float)]          = SqlDbType.Real;
        typeMap[typeof(double)]         = SqlDbType.Float;
        typeMap[typeof(TimeSpan)]       = SqlDbType.Time;
        /* ... and so on ... */
    }

    // Non-generic argument-based method
    public static SqlDbType GetDbType(Type giveType)
    {
        // Allow nullable types to be handled
        giveType = Nullable.GetUnderlyingType(giveType) ?? giveType;

        if (typeMap.ContainsKey(giveType))
        {
            return typeMap[giveType];
        }

        throw new ArgumentException($"{giveType.FullName} is not a supported .NET class");
    }

    // Generic version
    public static SqlDbType GetDbType<T>()
    {
        return GetDbType(typeof(T));
    }
}

这就是您的使用方式:

var sqlDbType = SqlHelper.GetDbType<string>();
// or:
var sqlDbType = SqlHelper.GetDbType(typeof(DateTime?));
// or:
var sqlDbType = SqlHelper.GetDbType(property.PropertyType);

编辑:我在考虑,这适用于 System.Data.SqlTypes 类型。我会把它留在这里,以防将来它对某人有所帮助。

我是这样做的:

object objDbValue = DbReader.GetValue(columnIndex);
Type sqlType = DbReader.GetFieldType(columnIndex);
Type clrType = null;

if (sqlType.Name.StartsWith("Sql"))
{   
    var objClrValue = objDbValue.GetType()
                                .GetProperty("Value")
                                .GetValue(objDbValue, null);
    clrType = objClrValue.GetType();
}

因为每个 SqlDbType 都有一个 .Value 属性,这是我使用反射来获取它的实际底层 CLR 类型。太糟糕了,SqlDbType 没有一些接口可以保存这个 .Value 属性 并且不需要反射。
它并不完美,但您不必手动创建、维护或填充字典。您可以在现有字典中查找类型,如果不存在,则使用 upper 方法自动添加映射。 几乎是自动生成的。
还处理 SQL 服务器将来可能收到的任何新类型。

似乎这种查找 table 已经可用,尽管不在 System.Data(或 .Object.Type)中,而是在 System.Web.

项目 -> 添加引用 -> System.Web -> 确定

然后https://msdn.microsoft.com/en-us/library/system.data.sqldbtype(v=vs.110).aspx也说

When setting command parameters, the SqlDbType and DbType are linked. Therefore, setting the DbType changes the SqlDbType to a supporting SqlDbType.

所以,这在理论上应该可行;)

using Microsoft.SqlServer.Server; // SqlDataRecord and SqlMetaData
using System;
using System.Collections; // IEnumerator and IEnumerable
using System.Collections.Generic; // general IEnumerable and IEnumerator
using System.Data; // DataTable and SqlDataType
using System.Data.SqlClient; // SqlConnection, SqlCommand, and SqlParameter
using System.Web.UI.WebControls; // for Parameters.Convert... functions

private static SqlDbType TypeToSqlDbType(Type t) {
    DbType dbtc = Parameters.ConvertTypeCodeToDbType(t.GetTypeCodeImpl());
    SqlParameter sp = new SqlParameter();
    // DbParameter dp = new DbParameter();
    // dp.DbType = dbtc;
    sp.DbType = dbtc;
    return sp.SqlDbType;
}

我的同事给了我尝试 属性 的 SqlParameter 的想法:

Func<Object, SqlDbType> getSqlType = val => new SqlParameter("Test", val).SqlDbType;
Func<Type, SqlDbType> getSqlType2 = type => new SqlParameter("Test", type.IsValueType?Activator.CreateInstance(type):null).SqlDbType;

//returns nvarchar...
Object obj = "valueToTest";
getSqlType(obj).Dump();
getSqlType2(typeof(String)).Dump();

//returns int...
obj = 4;
getSqlType(obj).Dump();
getSqlType2(typeof(Int32)).Dump();

//returns bigint...
obj = Int64.MaxValue;
getSqlType(obj).Dump();
getSqlType2(typeof(Int64)).Dump();

https://dotnetfiddle.net/8heM4H