tags:

views:

360

answers:

2

For f# to talk to a database, I presume you turn to some code that looks quite a lot like C# code, using some NET libraries (ado.net for example) and quite a lot of imperative code that has, by definition, quite a lot of side-effects..

Or am I missing something here? Has F# some beauty to offer in this domain also?

And would someone be so kind a to provide me with an example for both reading from an writing to a database?

+2  A: 

You may want to use the accepted answer in this question as a good starting point.

http://stackoverflow.com/questions/291445/f-beginner-retrieving-an-array-of-data-from-a-server

Depending on the database you are using you may get some other choices, but start with something fairly functional and you can improve on it as you gain experience.

James Black
+2  A: 

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#.

Joel Mueller