I\'m using F# 3.0 with .NET 4.5 beta, and I\'m trying to convert an F# quotation of type Expr<\'a -> \'b>
to a LINQ Expression
Can you post a more complete sample and also include the F# expression that you're trying to convert?
I tried to test the behaviour on .NET 4.5 using a minimal sample and it worked for me. Here is what I did:
I created new F# 3.0 project and copied Linq.fs
and Linq.fsi
from the 2.0 version of F# PowerPack. (Or is there a 3.0 version of the ToLinqExpression
method available somewhere in F# 3.0?)
I used the code from Daniel's earlier answer and called the function as follows:
let r = toLinq <@ fun x -> x + 1 @>
printfn "%A" r
This did not throw any exception and it printed x => (x + 1)
, which looks correct to me.
EDIT: To answer the updated question - both of the code samples that you referred to (mine and Daniel's) assume that the body of the quotation is an explicitly constructed function, so they only work on quotations of a specific structure: <@ fun x -> ... @>
.
You can fix the problem by using splicing in an explicitly constructed function. The following works for me:
let exp = <@ fun x -> x + 1 @>
let r = toLinq <@ fun a -> box ((%exp) a) @>
printfn "%A" r
This contains application of an F# function, so the generated Expression
contains a call to ToFSharpFunc
(which converts a delegate to an F# function) and then invocation of this. This may be an issue if you want Expression
that standard .NET tools can understand (in which case, you'd have to post-process the C# expression tree and remove these constructs).