Skip to content

Instantly share code, notes, and snippets.

@jshurst
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jshurst/fb671c06dc33e10b1f32 to your computer and use it in GitHub Desktop.
Save jshurst/fb671c06dc33e10b1f32 to your computer and use it in GitHub Desktop.
F# DB Record Mapping
//Taken from here: http://fssnip.net/5E
//Given any of this kind (record)
type product =
{ProductId:int;
ProductName:string;
SupplierID:int;
CategoryID:int;
QuantityPerUnit:string;
UnitPrice:decimal;
UnitsInStock:int;
UnitsOnOrder:int;
ReorderLevel:int;
Discontinued:bool}
//Read all records from a table an give an IEnumerable collection as output
let getAllRecords<'a>(tableName) (conn) =
use cmd = new SqlCommand(("Select * from " + tableName), conn)
use reader = cmd.ExecuteReader()
let recFields = typeof<'a>.GetMembers() |> Array.filter (fun (f:MemberInfo) -> f.MemberType.ToString() = "Property")
[while reader.Read() do yield (recFields |> Array.map (fun (f:MemberInfo) -> unbox (reader.[f.Name])))]
|> List.map (fun oArray -> Activator.CreateInstance(typeof<'a>, oArray))
|> Seq.ofList |> Seq.map (fun o -> o :?> 'a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment