1

如何将 , , , 等字符串转换"uniqueidentifier""timestamp"各自"image""money".net"sql_variant"数据类型?

我需要查询一个表以找出它包含的字段,然后将它们累积到一个列表中List<Column>Column是我写的一门课。所以我需要这个机制。

4

2 回答 2

4

使用 ExecuteReader 对目标列运行查询以获取 SqlDataReader,然后使用 GetFieldType(返回 .NET 数据类型)和 GetDataTypeName(返回相应的 SQL 服务器类型名称)。实际的类型映射是在 SqlClient 内部完成的——您可以使用反射来访问它,并希望它不会在 .NET 版本之间发生变化,但我不推荐它。

于 2009-11-17T08:36:40.040 回答
2

只需计算出您想要的类型(可能因您的数据库而异)并使用字典:

static reaodnly Dictionary<string, Type> NameToTypeMap = 
new Dictionary<string, Type>
{ 
    { "uniqueidentifier", typeof(Guid) },
    { "timestamp", typeof(DateTimeOffset) },
    { "image", typeof(byte[]) },
    // etc
};

请注意,这是假设您使用的是 C# 3,因为它使用集合初始化程序。如果您不使用 C# 3,请告诉我。

编辑:这是 C# 2 代码:

static Dictionary<string, Type> NameToTypeMap = GetTypeMap();

private static Dictionary<string, Type> GetTypeMap()
{ 
    Dictionary<string, Type> ret = new Dictionary<string, Type>();
    ret["uniqueidentifier"] = typeof(Guid);
    ret["timestamp"] = typeof(DateTimeOffset);
    ret["image"] = typeof(byte[]);
    // etc
    return ret;
}
于 2009-11-17T08:15:51.893 回答