如何动态访问F#.Data.SqlClient记录属性

时间:2014-12-19 10:12:27

标签: reflection f# fsharp.data.sqlclient

我通过F#Data SqlClient Type提供程序使用以下代码返回了一些数据Record

    open FSharp.Data

    [<Literal>]
    let connectionString = "..."
    [<Literal>]
    let linksQuery = "SELECT Id, TheName, ... FROM Links"

    type LinksQuery = SqlCommandProvider<linksQuery, connectionString>

    let result = (new LinksQuery())
                        .AsyncExecute() 
                        |> Async.RunSynchronously

    let first = result.[0]

我现在想要动态访问此first Record的属性 - 我需要哪些属性取决于某些用户输入 - 他们输入key

我知道我可以使用C#style Reflection执行此操作,代码如下:

   let theType = first.GetType()
   let theProp = theType.GetProperty("Item")
   let theValue = theProp.GetValue(first,  [| key |])
   // now use `theValue` (which is sometimes a string and sometimes an Option(string)

但是,我想知道我是否可以使用更简单的F#

来做到这一点

理想情况下,我想使用类似first.[key]的内容 - 但此语句会返回错误The field, constructor or member "Item" is not defined

0 个答案:

没有答案