【问题标题】:F# Downcasting elements of DataTableF# 向下转换 DataTable 的元素
【发布时间】:2017-04-07 11:25:51
【问题描述】:

我正在尝试从 SQL Server 2008 R2 上的存储过程返回数据。 (存储过程不能很好地与 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"

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

我认为做一些嵌套循环或者 .Map 或 .Iter 函数来遍历所有行和列并将值存储到正确的列数组中会很容易。 (如果有更好的方法来做到这一点 - 我觉得应该有 - 任何建议都会受到赞赏!)

但是返回的值是 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

【问题讨论】:

    标签: datatable f# downcast


    【解决方案1】:

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

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

    一旦你弄清楚了类型。

    【讨论】:

    • 我明白了。我想无论如何我都需要对列名进行一些映射才能知道如何处理内容,所以无论如何动态向下转换可能不会有太多收获。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2015-08-30
    • 2016-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多