15

I'm trying to use F# to construct a query against a database, but I can't get even the simplest of queries to compile.

I can construct a C# query like this:

from c in Categories
select c

Everything works fine. However, when I try to do what should be the same thing in F#:

query { for c in Categories do
        select c }

I get the following error:

Invalid use of a type name and/or object constructor. If necessary use 'new' and apply the constructor to its arguments, e.g. 'new Type(args)'. The required signature is: Categories() : unit.

LINQPad comes bundled with a number of samples, but none of the F# samples actually show how to use it to query against a database. I've looked around the internet, also, but I can't find any examples using F# to query a database in LINQPad. What am I missing here?

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331

2 Answers2

14

Out of curiosity I decided to try and get something working with F# in LinqPad. I was able to get it working by selecting "F# Program" instead of F# expression. I'm sure it's possible using just an expression, but I am 100% unfamiliar with F# so I just did enough to get a working example. Selecting this option gave me a single line of:

let dc = new TypedDataContext()

From there, I followed this example page to get this query working/executing:

let dc = new TypedDataContext()

let query1 = query { for c in dc.MyTable do
                     select c }

query1
|> Seq.iter (fun x -> printfn "SomeField: %s" x.SomeField)
Ocelot20
  • 10,510
  • 11
  • 55
  • 96
  • 3
    I figured there was probably some sort of magic word I had to use; turns out `dc` was it. In 'F# Expression' mode, `query { for c in dc.Categories do select c }` works fine. Thanks for pointing me in the right direction. – p.s.w.g Oct 15 '13 at 17:44
  • 2
    No problem. You'll probably also notice the warning you get using `dc.Categories` about not using the `this` keyword. Looks like similar to C#, the `DataContext` is actually scoped to `this`, so you can do `this.Catagories` and get rid of the warning. – Ocelot20 Oct 15 '13 at 18:54
3

You just need to add "this." in front of the mapped table if you want to run it as a F# Expression in LINQPad.

query { for c in this.Categories do
        select c }
B Diehl
  • 686
  • 5
  • 6