F# 向下转换 DataTable 的元素

F# Downcasting elements of DataTable

我正在尝试从 SQL Server 2008 R2 上的存储过程中 return 数据。 (存储过程在 Microsoft.FSharp.Data.TypeProviders 上表现不佳,我浪费了整个上午的大部分时间 this seemingly futile path。)

所以我从下面的代码中得到了一系列表格:

open System.Data
open System.Data.SqlClient

let connString = @"Data Source=someserver;Initial Catalog=somedb;Integrated Security=True"
let conn = new SqlConnection(connString)

let GetTables spName baseTableName =
    use comm = new SqlCommand(spName, conn, CommandType=CommandType.StoredProcedure)
    comm.CommandTimeout <- 90
    comm.Parameters.AddWithValue("@TableName", baseTableName) |> ignore
    use adapter = new SqlDataAdapter(comm)
    use dataSet = new DataSet()
    adapter.Fill(dataSet) |> ignore
    dataSet.Tables |> Seq.cast<DataTable>

let tableSeq = GetTables @"dbo.uspGetPremium" "0123_Premium_99"

最终我想将每一列提取到一个单独的数组(或者可能是列表或序列)中。有些列是字符串,有些是整数,有些是浮点数。

我想做一些嵌套循环或者 .Map 或 .Iter 函数来遍历所有行和列并将值存储到适当的列数组会很容易。 (如果有更好的方法——我觉得应该有——欢迎任何建议!)

但是 returned 值是 obj 类型,我不知道如何向下转换为正确的类型。

let table0 = tableSeq |> Seq.item 0
table0.Rows.[0].[1];;

val table0 : DataTable = Table
val it : obj = 134

从下面的代码中,我可以告诉 Columns。[1]具有类型 System.Int32.

table0.Columns.[1].DataType

但是,如果我从该列中取出第一个元素,我该如何向下转换为上面 .DataType 中指定的相同类型?这失败了:

table0.Rows.[0].[1] :?> table0.Columns.[1].DataType

转换的目标类型必须是静态已知的(它不能像您使用的那样是任意运行时表达式),因此您必须使用

table0.Rows.[0].[1] :?> int

一旦你弄清楚了类型。