Stavo cercando una conversione intelligente tra .Net System.Type e SqlDbType. Quello che ho trovato è stata la seguente idea:Tipo di sistema .NET a 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;
}
Il codice di cui sopra non è veramente bello ed è un odore di codice, che è il motivo per cui ho scritto la seguente funzione, ingenuo, non è intelligente, ma utile, sulla base di 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)];
}
Qualcuno ha idea di come ottenere lo stesso risultato in modo più pulito, migliore e più bello?
Fare conversione dizionario è OK. Fatto * una volta * in una vita. :) (meno c'è un cambiamento) – Ian
Se la mia risposta l'ha aiutata, contrassegnala come risposta selezionata. :) –