4

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?

asked Nov 26, 2009 at 7:23
1
  • 9
    No, it's half an octave higher. :) Commented Nov 26, 2009 at 7:32

2 Answers 2

4

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

answered Dec 1, 2009 at 5:54
2

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

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.

answered Nov 26, 2009 at 7:38

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.