Search code examples
f#type-providers

How can I transform an object of a given type to a record?


I get a IEnumerable of object from using a SqlCommandProvider. Those objects match my rows and columns. Lets called it B. In my program I created a type matching those columns too. Lets call this record A. How can I actually transform/cast/construct a record c of type A based on values from B?

type A = {k: int; c: string}

let a:A = { k = 1; c = "c" }
let b = {| k = 1; c = "c" |} // lets say that this one simulate the sql's object
let c:A = b

printfn "%A" a
printfn "%A" b
printfn "%A" c

Try it online!

I got an error of type mismatch:

error FS0001: This expression was expected to have type 'A' but here has type '{|c : string ; k : int|}'

Full sample code with the provider:

type A = {k: int; c: string}

let toA c =
    (A)c // ???

do
    use cmd = new SqlCommandProvider<"
        SELECT k, c
        FROM Examples
    " , connectionString>(connectionString)

    cmd.Execute() |> Seq.map toA

sql table if it matters:

k c
0 a
1 b

I read the doc without finding a solution to my problem. Maybe it is a comprehension problem.


Solution

  • A working solution is to construct a record from the object:

    let toA c =
        {k = c.k; c = c.c }
    
    cmd.Execute()
    |> Seq.map toA