2009-10-15 22 views

回答

1

我在Dot Net PulseCodeProject找到了幾個選項。我最終與CodeProject上的代碼轉換,從VB.NET到C#去:

private SqlDbType GetDBType(System.Type theType) 
{ 
    System.Data.SqlClient.SqlParameter p1; 
    System.ComponentModel.TypeConverter tc; 
    p1 = new System.Data.SqlClient.SqlParameter(); 
    tc = System.ComponentModel.TypeDescriptor.GetConverter(p1.DbType); 
    if (tc.CanConvertFrom(theType)) { 
     p1.DbType = (DbType)tc.ConvertFrom(theType.Name); 
    } else { 
     //Try brute force 
     try { 
      p1.DbType = (DbType)tc.ConvertFrom(theType.Name); 
     } 
     catch (Exception) { 
      //Do Nothing; will return NVarChar as default 
     } 
    } 
    return p1.SqlDbType; 
} 

我真的很希望能找到,有一些不可告人的祕密System.Data.SqlClient的方法來進行轉換,我只是失蹤了。

+0

任何人得到這個編譯?由於tc.ConvertFrom返回一個對象,我得到「不能隱式轉換類型'對象'到'System.Data.DbType'。存在明確的轉換(你是否缺少一個轉換?)」 – 2016-01-28 14:59:45

+1

@AlanMacdonald:對不起 - 看到我的編輯, – 2016-01-28 15:34:07

+0

謝謝。我擔心這可能表明這個成員沒有得到很好的測試,所以我現在已經去了馬特米勒的回答 – 2016-01-28 16:08:01

6

沒有現成的方法來做到這一點 - 您需要滾動功能來執行此操作,或者緩存Dictionary<Type, SqlDbType>以進行查找。

0

您可以複製的數據表像

DataTable newdt = DataTable.Copy(); 

並與不同數據類型中刪除列,並將它們添加到您的newdt。

只是我過去一直在解決它的一種方法。

1

像這樣的東西可能是一個好的開始。這是不全面的,但讓我的地方,我需要去:

Dictionary<Type, SqlDbType> GetSQLTypeConversionMap() 
{ 
    var result = new Dictionary<Type, SqlDbType>(); 
    result.Add(typeof(string), SqlDbType.VarChar); 
    result.Add(typeof(Int16), SqlDbType.Int); 
    result.Add(typeof(Int32), SqlDbType.Int); 
    result.Add(typeof(DateTime), SqlDbType.DateTime2); 
    return result; 
} 
8

這裏是我的解決方案,它使用內置的.NET功能:

/// <summary> 
/// Get the equivalent SQL data type of the given type. 
/// </summary> 
/// <param name="type">Type to get the SQL type equivalent of</param> 
public static SqlDbType GetSqlType(Type type) 
{ 
    if (type == typeof(string)) 
     return SqlDbType.NVarChar; 

    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) 
     type = Nullable.GetUnderlyingType(type); 

    var param = new SqlParameter("", Activator.CreateInstance(type)); 
    return param.SqlDbType; 
} 

當心,這將始終設置字符串爲nvarchar (這個問題的任何通用解決方案都會有相同的問題,因爲無法知道正確的SqlDbType)。當將這個參數化的SELECT或UPDATE查詢用於不是NVarChar的列時,SqlServer的性能在比較NChar/NVarChar和Char/VarChar類型時會拖延,因爲它正在爲每次比較轉換值。最近這讓我感到困難(一個過程從花費4分鐘到140+分鐘),所以當你可以的時候,一定要明確你的char參數類型!我會想象其他類似的類型可能會有同樣的問題,但沒有任何問題導致我(還)。

+0

編輯刪除我的一小時後被鎖定的意外downvote。 – 2017-04-25 19:22:59

0

回答this thread,但它是非常簡短,所以我會在這裏重新報價是:

可以使用方法ConvertTypeCodeToDbType轉換TypeCodeDbTypeSystem.Web.UI.WebControls.Parameter類:Parameter.ConvertTypeCodeToDbType方法。要獲得TypeCode,您可以使用方法Type.GetTypeCode(Type type)