-
-
Save ITSecMedia/bbd8b63ffb4d5a92829b9966977f8d1e to your computer and use it in GitHub Desktop.
F# extensions for Dapper
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 Dapper.Extensions | |
open System | |
open System.Data.SqlClient | |
open Dapper | |
let extractValue (x:obj) = | |
match x with | |
| null -> null | |
| _ -> match x.GetType().GetProperty("Value") with | |
| null -> x | |
| prop -> prop.GetValue(x) | |
let (+>) (map:Map<string, obj>) (key,value) = map.Add(key, extractValue value) | |
let singleParam (key, value) = (Map.empty) +> (key,value) | |
type OptionHandler<'T>() = | |
inherit SqlMapper.TypeHandler<option<'T>>() | |
override __.SetValue(param, value) = | |
let valueOrNull = | |
match value with | |
| Some x -> box x | |
| None -> null | |
param.Value <- valueOrNull | |
override __.Parse value = | |
if isNull value || value = box DBNull.Value | |
then None | |
else Some (value :?> 'T) | |
let registerTypeHandlers() = | |
SqlMapper.AddTypeHandler (OptionHandler<Guid>()) | |
SqlMapper.AddTypeHandler (OptionHandler<int64>()) | |
SqlMapper.AddTypeHandler (OptionHandler<int>()) | |
SqlMapper.AddTypeHandler (OptionHandler<string>()) | |
SqlMapper.AddTypeHandler (OptionHandler<DateTime>()) | |
let safeSqlConnection string = | |
registerTypeHandlers() | |
new SqlConnection(string) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment