2
votes

I'm currently trying out the SqlDataConnection type provider, and was wondering how to display these types.

Is there some way I can have my calls to printfn "%A" display something more meaningful than the type name?

1
Have you attempted annotating the type provider with a StructuredFormatDisplay attribute? - bytebuster

1 Answers

2
votes

I do not think there is a way to intercept the behaviour of printfn "%A" for existing types generated by a type provider (that you cannot modify). If you could modify the type provider, then you could change it to generate the StructuredFormatDisplay attribute for the generated types, but that's not possible for SqlDataConnection.

If you're using it in F# Interactive, then you can use fsi.AddPrintTransformer to define how individual values are printed when they are a result of some computation. For example:

// Using Northwind database as a sample
type DB = SqlDataConnection<"Data Source=.\\SQLExpress;Initial Catalog=Northwind;...">
let db = DB.GetDataContext()

// A simple formatter that creates a list with property names and values
let formatAny (o:obj) = 
  [ for p in o.GetType().GetProperties() ->
      p.Name, p.GetValue(o) ]

// Print all Northwind products using the formatter
fsi.AddPrintTransformer(fun (p:DB.ServiceTypes.Products) ->
  formatAny p |> box)

// Take the first product - will be printed using custom formatter
query { for p in db.Products do head }

The specified PrintTransformer is only used when you get the value as a result in F# interactive. It will also work when you write query { .. } |> List.ofSeq for queries that return multiple objects. But for printfn "%A", you'll have to call the conversion function (like formatAny) explicitly...