Because there isn't language support for dynamic, this is slightly more involved in F#. (I recommend reading the docs on DynamicAttribute
.) Here's a translation:
open System.Collections.Generic
open System.Data
open System.Dynamic
open System.Runtime.CompilerServices
[<CompiledName("ToDynamic")>]
let toDynamic (reader: IDataReader) : [<return: Dynamic([|false;true|])>] ResizeArray<obj> =
let results = ResizeArray<obj>()
let rec loop() =
if reader.Read() then
let obj = ExpandoObject() :> IDictionary<_,_>
for i = 0 to reader.FieldCount - 1 do
obj.Add(reader.GetName(i), if reader.IsDBNull(i) then null else reader.[i])
results.Add(obj)
loop()
else results
loop()
If you just want dynamic access to the values in an IDataReader
, a more elegant solution in F# would be to overload the dynamic operator:
let (?) (reader: IDataReader) (name: string) =
match reader.[name] with
| :? DBNull -> Unchecked.defaultof<_>
| value -> unbox value
//Usage: reader?Id