When I needed to do some database access from F# in a test project, I ended up using LINQ to SQL from F#. I just added a 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 reference the assemblies FSharp.PowerPack and FSharp.PowerPack.Linq. Then you can open Microsoft.FSharp.Linq
.
Here's an example that parses "Site" tags out of an XDocument, creating instances of the Site
class (a C# generated LINQ to SQL class), 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 though it's using C# classes, it's not entirely imperative code.
Here's an example of using the F# version of LINQ to find the maximum rank of all the site entries in the database. Yes, this does get translated to SQL and executed in the database.
use db = new SomeDataContext()
Query.query <@ seq { for s in db.Sites -> s.Rank } |> Seq.max @>
Finally, here's some more information on LINQ with F#.