Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IQueryable lambda style in F#

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?

like image 652
user826840 Avatar asked Jun 02 '26 11:06

user826840


1 Answers

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

like image 112
Tuomas Hietanen Avatar answered Jun 05 '26 01:06

Tuomas Hietanen