Question

I have the following code and I want the function getCol1Col2 returns tuple of Col1, Col2 instead of Linq.IQueryable<>. How to write it? This is newbie question.

And how to returns none if there is no row found in the database table?

open System
open System.Data
open System.Data.Linq
open Microsoft.FSharp.Data.TypeProviders
open Microsoft.FSharp.Linq
open System.Net
open System.IO

type dbSchema = SqlDataConnection<"Data Source=server;Initial Catalog=db;Integrated Security=SSPI;">

let getFirstCol1Col2 =
    let db = dbSchema.GetDataContext()
    db.DataContext.Log <- System.Console.Out
    let query = query { 
        for row in db.MyTable do 
        where (row.ID = 1) 
        select (row.Col1, row.Col2) }
    query //.... Need to return the tuple of Col1, Col2
Was it helpful?

Solution

There is a standard query operator headOrDefault which returns the first result or default value. Sadly, the default value of tuple will be null (I think), so this will be unsafe. You could return an option type, because the default value of an option type is None:

let query = 
  query { for row in db.MyTable do 
          where (row.ID = 1) 
          select (Some(row.Col1, row.Col2))
          headOrDefault }

Alternatively, you can use this nice extension which adds headOrNone that does exactly what you want - returns Some(col1, col2) if there are some rows or None otherwise:

let query = 
  query { for row in db.MyTable do 
          where (row.ID = 1) 
          select (Some(row.Col1, row.Col2))
          headOrNone }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top