4

Is it possible to use lambda-style querying of IQueryable objects in F#, instead of query expressions? Something like:

type schema = SqlDataConnection<"Data Source=(local);Initial Catalog=MyDatabase;Integrated Security=true;">
let db = schema.GetDataContext()
let q = db.MyTable |> Seq.filter (fun r -> r.id < 100) |> Seq.take 10
let result = q |> List.ofSeq

When I profile this it is doing select * from MyTable so I assume the filter and take are being executed on IEnumerables not IQueryables?

Or is the only way to fix this to use query {} without lambdas?

user826840
  • 1,233
  • 2
  • 13
  • 28
  • 3
    Doesn't syntax like `db.MyTable.Where(fun r -> r.id < 100).Take(10)` work, similar to C#? – Sedat Kapanoglu Jul 20 '14 at 10:32
  • 1
    Ah yes it does! That never occurred to me.. but just out of interest, this can't be done with 'proper' F# piping? I guess when you start calling `Seq.filter` you are effectively calling `.AsEnumerable()`? – user826840 Jul 20 '14 at 10:41
  • I don't think it's an issue with F# syntax but more about `Seq` using `IEnumerable` rather than `IQueryable`. conversion to `IEnumerable` forces the query to be executed. Perhaps you could find a solution around this: http://stackoverflow.com/a/13828080/54937 – Sedat Kapanoglu Jul 20 '14 at 10:46
  • 1
    Thanks, but that looks a bit advanced for me. Only started F# yesterday. Is it technically possible to write something like `Query.filter` that would do a linq `.Where()`? – user826840 Jul 20 '14 at 11:39

1 Answers1

1

The reason is that Seq.toList calls the data struncture GetEnumerator() and there is something like this inside the type (pseudo, not the actual source):

type SqlDataConnection<...>(...) =
    interface seq<'T> with
        member __.GetEnumerator() = executeSQL()

If you want to operate with IQueryable instead of IEnumerable, there is the query-syntax in F#:

query {
    for r in db.MyTable do
    where (r.id < 100)
    take 10
} |> Seq.toList

More details: https://learn.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/query-expressions

Tuomas Hietanen
  • 4,650
  • 2
  • 35
  • 43