Tôi đang tìm kiếm một chuyển đổi thông minh giữa .Net System.Type và SqlDbType. Những gì tôi thấy đó là ý tưởng sau đây:Loại Hệ thống .NET cho 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;
}
Đoạn mã trên là không thực sự tốt đẹp và là một mùi mã, đó là lý do tôi đã viết như sau, chức năng ngây thơ, không thông minh, nhưng hữu ích, dựa trên 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)];
}
Có ai có ý tưởng làm sao để có được kết quả tương tự một cách sạch hơn, tốt hơn và tốt đẹp hơn không?
Làm chuyển đổi từ điển là OK. Xong * một lần * trong một thời gian cuộc sống. :) (ít có thay đổi) – Ian
Nếu câu trả lời của tôi đã giúp bạn, hãy đánh dấu nó là câu trả lời bạn đã chọn. :) –