Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper dot net query in F#

Tags:

f#

dapper

I'm trying to use Dapper dot net in F# to perform a simple SQLite query. Dapper returns a collection of dynamic objects: using them in C# is straightforward, but from what I understood F# has no dynamic property lookup implementation out-of-the-box.

This is working but I suppose there are better ways to do this without resorting to reflection:

let (?) x prop =
    let flags = BindingFlags.GetProperty ||| BindingFlags.InvokeMethod
    x.GetType().InvokeMember(prop, flags, null, x, [||])

let doQuery () =
    //...
    let conn = new SQLiteConnection (connString)
    conn.Open ()

    conn.Query("select first_name from customers")
        |> Seq.map (fun c -> c ? first_name)
        |> List.ofSeq

What is the best way to implement the ? operator in this case?

like image 867
Francesco De Vittori Avatar asked Feb 20 '12 16:02

Francesco De Vittori


2 Answers

This thread consists of several solutions for your problem. Especially, FSharp.Interop.Dynamic is available on NuGet and ready to use.

like image 65
pad Avatar answered Nov 08 '22 15:11

pad


When using Dapper with F#, you can specify your query parameters using F# Anonymous Records and map the results directly to an F# Record, like so:

[<CLIMutable>]
type CustomerDto = 
    {
        FirstName: string
    }

let selectSql = "select first_name as FirstName from customers where first_name = @firstName"

conn.Query<CustomerDto>(selectSql, {|firstName = "Francesco"|})

Note that F# Anonymous Records were introduced in F# 4.6.

like image 34
Sean Kearon Avatar answered Nov 08 '22 16:11

Sean Kearon