Last active
August 29, 2015 14:03
-
-
Save jshurst/fb671c06dc33e10b1f32 to your computer and use it in GitHub Desktop.
F# DB Record Mapping
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
//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