NullReferenceException in F# interactive

90 Views Asked by At

I'm using microsoft.data.sqlclient library. I’m trying to execute this simple code in F# interactive:

#r @"C:\Users\micha\.nuget\packages\microsoft.data.sqlclient\5.1.0\ref\net6.0\Microsoft.Data.SqlClient.dll"

open Microsoft.Data.SqlClient

let conn = new SqlConnection("CONN_STR")
conn.Open()
let state = conn.State

Everything blowns up at the last step:

System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.Data.SqlClient.SqlConnection.get_State() in D:\a\_work\1\s\src\Microsoft.Data.SqlClient\netcore\ref\Microsoft.Data.SqlClient.cs:line 889
   at <StartupCode$FSI_0006>.$FSI_0006.main@() in C:\some\path\stdin:line 3
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
   at System.Reflection.MethodInvoker.Invoke(Object obj, IntPtr* args, BindingFlags invokeAttr)
Stopped due to error

Everything is working if I just execute the same code as normal console app

Why I'm getting this error when I'm doing that in F# interactive?

2

There are 2 best solutions below

2
Jim Foye On BEST ANSWER

I stop getting exceptions after making two changes:

Reference the package like this:

#r "nuget: Microsoft.Data.SqlClient"

Switch FSI to use .Net Core (Tools|Options|F# Tools|F# Interactive -> set "Use .NET Core Scripting" to True)

I have no idea why.

1
Tarmil On

As @Jim Foye pointed out, the best way to go is to reference the package with #r "nuget:".

As for why your original code throws an exception: the assemblies in the ref folder of a package, when there is one, are so-called "reference assemblies". They contain all the same classes and methods as the corresponding runtime assemblies except with invalid implementations, and they are only meant to be used during compilation, not at runtime. The assemblies that are actually used at runtime are in the lib folder.

Related Questions in F#

Related Questions in F#-INTERACTIVE

Related Questions in F#-3.0