Created
July 16, 2019 13:40
-
-
Save AlbertoDePena/5745eee9e7dfc029fe473cd33ae789f7 to your computer and use it in GitHub Desktop.
Dapper with FSharp
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
open System | |
open System.Collections.Generic | |
open System.Data.SqlClient | |
open Dapper | |
open System.Data | |
open FSharp.Control.Tasks.V2.ContextInsensitive | |
let ExitCode = 0 | |
let DbConnectionString = "Server=localhost;Database=EventStore;Trusted_Connection=True;" | |
[<CLIMutable>] | |
type StreamDTO = { Name: string; Version: int; CreatedAt : DateTimeOffset; UpdatedAt: DateTimeOffset Nullable } | |
[<CLIMutable>] | |
type StreamQuery = { StreamName: string } | |
let dapperQuery<'Result> (query: string) (connection: IDbConnection) = | |
connection.QueryAsync<'Result>(query) | |
let dapperParametrizedQuery<'Result> (query: string) (param: obj) (connection: IDbConnection) = | |
connection.QueryAsync<'Result>(query, param) | |
let dapperMapParametrizedQuery<'Result> (query: string) (parameters : Map<string, _>) (connection: IDbConnection) = | |
let dictionary = Dictionary<string, obj>() | |
for parameter in parameters do dictionary.Add(parameter.Key, parameter.Value) | |
connection |> dapperParametrizedQuery<'Result> query dictionary | |
let getConnection () = | |
task { | |
let connection = new SqlConnection(DbConnectionString) | |
do! connection.OpenAsync() | |
return connection | |
} | |
let getStreams () = | |
task { | |
use! connection = getConnection () | |
let query = "select * from dbo.Streams" | |
let! results = dapperQuery<StreamDTO> query connection | |
return results | |
} | |
let getStream (streamName: string) = | |
task { | |
use! connection = getConnection () | |
let query = "select * from dbo.Streams where Name = @StreamName" | |
//let args = Map ["StreamName", streamName] | |
let args = { StreamName = streamName } | |
//let! results = dapperMapParametrizedQuery<StreamDTO> query args connection | |
let! results = dapperParametrizedQuery<StreamDTO> query args connection | |
return results | |
} | |
[<EntryPoint>] | |
let main argv = | |
getStream "Demo" | |
|> Async.AwaitTask | |
|> Async.RunSynchronously | |
|> printfn "%A" | |
printfn "Press ENTER to exit..." | |
Console.ReadKey() |> ignore | |
ExitCode |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment