문제

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
도움이 되었습니까?

해결책

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 }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top