Last active
April 21, 2022 02:58
-
-
Save vbfox/1e9f42f6dcdd9efd6660 to your computer and use it in GitHub Desktop.
Minimal dapper in F#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module DapperFSharp = | |
open System.Data.SqlClient | |
open System.Dynamic | |
open System.Collections.Generic | |
open Dapper | |
let dapperQuery<'Result> (query:string) (connection:SqlConnection) = | |
connection.Query<'Result>(query) | |
let dapperParametrizedQuery<'Result> (query:string) (param:obj) (connection:SqlConnection) : 'Result seq = | |
connection.Query<'Result>(query, param) | |
let dapperMapParametrizedQuery<'Result> (query:string) (param : Map<string,_>) (connection:SqlConnection) : 'Result seq = | |
let expando = ExpandoObject() | |
let expandoDictionary = expando :> IDictionary<string,obj> | |
for paramValue in param do | |
expandoDictionary.Add(paramValue.Key, paramValue.Value :> obj) | |
connection |> dapperParametrizedQuery query expando |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type User = { UserId:string } | |
let getUsers connection = | |
connection | |
|> dapperQuery<User> "SELECT UserID From tbUser" | |
let getUser userId connection = | |
connection | |
|> dapperMapParametrizedQuery<User> "SELECT UserID From tbUser WHERE UserId = @UserId" (Map ["UserId", userId]) | |
|> Seq.head | |
type UserSelectArgs = { SelectedUserId:string} | |
let getUser' userId connection = | |
connection | |
|> dapperParametrizedQuery<User> "SELECT UserID From tbUser WHERE UserId = @SelectedUserId" {SelectedUserId=userId} | |
|> Seq.head |
This looks useful. I'm trying to port a C# Dapper library using the Unit of Work pattern which is how I ended up here. What's missing (for me) is a way to wrap this up with transactions.
Definitely would be a plus to add the "chrome" around these snippets. They're very helpful. New users can add
open System.Data.SqlClient
open Dapper
open Npgsql
let connString = "Host=localhost;Database=exampleDB;Username=postgres;Password=example"
let connection = new NpgsqlConnection(connString)
connection.Open()
Note: You'll also need to install Npgsql: dotnet add package Npgsql --version 3.2.7
if you're using Postgres, like I am.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It would be nice if the sample script included an example of how to run the functions (including a sample connection string).