2

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
4

1 回答 1

1

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

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

或者,您可以使用这个不错的扩展,它添加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 }
于 2013-09-06T00:07:07.710 回答