Is F # database programming the same as C # database programming?

For f # to talk to the database, I assume that you go to some code that is very similar to C # code using some NET libraries (like ado.net) and quite a lot of imperative code, which, by definition, is pretty many side effects.

Or am I missing something? Does F # have some beauty in this domain?

And would anyone be so kind as to provide me with an example to read from write to database?

+4
source share
2 answers

You can use the accepted answer in this question as a good starting point.

F # Novice: getting an array of data from the server

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

+2
source

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

+4
source

All Articles