How to access F#.Data.SqlClient Record properties dynamically

255 views Asked by At

I've got some data Records returned via an F# Data SqlClient Type provider using code like:

    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]

I'd now like to access the properties of this first Record dynamically - which properties I need depends on some user input - they enter a key.

I know I can do this using C# style Reflection with code like:

   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)

However, I'm wondering if there is any way I can do this using simpler F#

Ideally I'd like to use something like first.[key] - but this statement returns the error The field, constructor or member "Item" is not defined

0

There are 0 answers