简体   繁体   中英

f# convert seq obj to seq records

I am trying to read data from database and convert them to seq of records. When executing

open FSharp.Data
open FSharp.Data.SqlClient


type foo = {name:int; author:int}

[<Literal>]
let query = "Select * from Authors"

[<Literal>]//DESKTOP-5RIV0K1
let connectionString = "Data Source=DESKTOP-5RIV0K1;Initial Catalog=TestBase;Integrated Security=True"

let cmd = new SqlCommandProvider<query,connectionString>(connectionString)

let result = cmd.Execute() |> printfn "%A"

result

I get

seq
  [{ AuthorID = 1; Name = Some "2" }; { AuthorID = 2; Name = Some "3" };
   { AuthorID = 3; Name = Some "4" }] 

But when I am trying to convert seq obj to seq foo with code below

let result = 
    for item in cmd.Execute() do
    match item.Name, item.AuthorID with
        | Some itemName, Some itemAuthor ->
            {name = itemName; author = Some itemAuthor }
        | _ -> ()

I get error

Some itemAuthor

Error FS0001 This expression was expected to have type 'int' but here has type ''a option'

What I am doing wrong?

You are trying to match records that look like this...

{ AuthorID = 1; Name = Some "2" }

...using a pattern that looks like this...

| Some itemName, Some itemAuthor ->

Notice that your AuthorID is an integer. It is not an Option<int> . Consequently, the pattern with two Some values is not compatible. You should have a pattern like this instead...

| Some itemName, itemAuthor ->

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM