简单的答案是否定的,您必须手动进行转换。有一个完整列表 SQL Server 数据类型映射here。
我能想到的最简单的方法是创建几个帮助类来处理转换。 SqlExtension 类包含 ToType 方法,将 SqlDbType 转换为 Type。
public static class SqlExtensions
{
private static readonly IDictionary<SqlDbType, Type> TypeMap = new Dictionary<SqlDbType, Type>
{
{ SqlDbType.TinyInt, typeof(byte) },
{ SqlDbType.SmallInt, typeof(short) },
{ SqlDbType.Int, typeof(int)},
{ SqlDbType.BigInt,typeof(long) },
{ SqlDbType.Image, typeof(byte[])},
{ SqlDbType.Bit, typeof(bool)},
{ SqlDbType.DateTime, typeof(DateTime)},
{ SqlDbType.DateTime2, typeof(DateTime)},
{ SqlDbType.DateTimeOffset, typeof(DateTimeOffset)},
{ SqlDbType.NVarChar,typeof(string) },
{ SqlDbType.VarChar, typeof(string)},
{ SqlDbType.Text, typeof(string)},
{ SqlDbType.NText, typeof(string)},
{ SqlDbType.Char, typeof(char)},
{ SqlDbType.NChar, typeof(char)},
{ SqlDbType.Money, typeof(decimal)},
{ SqlDbType.Real, typeof(float)},
{ SqlDbType.Float, typeof(double)},
{ SqlDbType.Time, typeof(TimeSpan)}
// add the rest here
};
public static Type ToType(this SqlDbType type)
{
if (TypeMap.ContainsKey(type))
{
return TypeMap[type];
}
throw new ArgumentException($"{type} is not a supported");
}
}
TypeExtensions 类有一个扩展方法来获取类型的默认值(作为对象返回)。
public static class TypeExtensions
{
public static object GetDefault(this Type t)
{
Func<object> f = GetDefault<object>; // quick hack to get generic method
return f.Method.GetGenericMethodDefinition().MakeGenericMethod(t).Invoke(null, null);
}
private static T GetDefault<T>()
{
return default(T);
}
}
那么只需像SqlDbType.Bit.ToType().GetDefault().ToString()那样将调用链接在一起即可
class Program
{
static void Main(string[] args)
{
var type = SqlDbType.Bit.ToType();
Console.Write(SqlDbType.Bit.ToType().GetDefault().ToString());
}
}