获取第一行的列?

时间:2013-09-05 22:46:46

标签: f# type-providers f#-3.0

我有以下代码,我希望函数getCol1Col2返回Col1, Col2而不是Linq.IQueryable<>的元组。怎么写呢?这是新手问题。

如果在数据库表中找不到行,如何返回none?

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

1 个答案:

答案 0 :(得分:1)

有一个标准查询运算符headOrDefault,它返回第一个结果或默认值。遗憾的是,元组的默认值为null(我认为),所以这将是不安全的。您可以返回选项类型,因为选项类型的默认值为None

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

或者,您可以使用this nice extension添加完全符合您要求的headOrNone - 如果有某些行则返回Some(col1, col2),否则返回None

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