Paul Hunt
Paul Hunt

Reputation: 3555

Fixing PlatformNotSupportedException when referencing System.Data.SqlClient from C# Azure Function

I am creating an Azure Function in C# using a target framework of netstandard2.0 in a Windows 10 environment. The function calls a method that's in another class library and that method creates an instance of SqlConnection. When I run the function I get the following exception:

Microsoft.Azure.WebJobs.Host.FunctionInvocationException : Exception while executing function: Functions.RefreshImages ---> System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation. ---> System.PlatformNotSupportedException : System.Data.SqlClient is not supported on this platform. at System.Data.SqlClient.SqlConnection..ctor(String connectionString)......

Obviously SqlConnection is supported on Windows so I assume there's something else going on here.

Upvotes: 5

Views: 9715

Answers (2)

Louis Somers
Louis Somers

Reputation: 2964

This happens when a .Net Standard lib that uses a SqlConnection is loaded dynamically via reflection. The .Net Standard lib will typically reference System.Data.SqlClient which seems to be a dummy lib without actual implementation. It apparently ensures that the lib will compile on all platforms, including those without Registry and other platform specific stuff that the real SqlClient implementation relies on.

The easiest solution I can find is to add a reference to the Microsoft.Data.SqlClient NuGet package in the host application (the .Net core application that dynamically loads the .Net standard lib).

You may see a small yellow warning exclamation icon in the Solution explorer because Visual Studio thinks you are not using the lib and if you use the "Remove Unused References" feature it will also suggest removing the package. There is a feature to suppress warnings in the PropertyGrid, but I cannot figure out wat number should be filled in since the warning does not appear in the error list when compiling...

Upvotes: 4

Connor McMahon
Connor McMahon

Reputation: 1358

It looks like this is related to loading a SQL connection via reflection in .NET core (you are running on netstandard2.0 but the principle should still be the same).

Upvotes: 1

Related Questions