When I needed to access the database from F # in a test project, I ended up using LINQ to SQL from F #. I simply added the C # project to the solution, put the DataContext in the C # project, and used the generated C # LINQ to SQL classes in my F # project.
First you need to refer to the FSharp.PowerPack and FSharp.PowerPack.Linq builds . Then you can open Microsoft.FSharp.Linq .
Here is an example that parses the "Site" tags from an XDocument, creating instances of the Site class (generated by the C # LINQ to SQL class) and then inserting them into the database using the L2S data context.
let sites = doc.Descendants(ns + "Site") |> Seq.map (fun el -> new Site ( Url = xstr(el.Element(ns + "DataUrl")), Rank = xint(el.Element(ns + "Rank")) )) use db = new SomeDataContext() db.Sites.InsertAllOnSubmit(sites) db.SubmitChanges()
As you can see, even if it uses C # classes, this is not entirely imperative code.
Here's an example of using the F # version for LINQ to find the maximum rank of all site records in the database. Yes, it translates to SQL and runs in the database.
use db = new SomeDataContext() Query.query <@ seq { for s in db.Sites -> s.Rank } |> Seq.max @>
Finally, here is more info on LINQ with F # .
source share