SqlClient: Migrating from .NET5 to .NET6 throws PlatformNotSupported_DataSqlClient exception on startup in linux

Describe the bug

After migration from .NET5 to .NET6 any attempt to run the app ends with System.PlatformNotSupportedException: Strings.PlatformNotSupported_DataSqlClient on Linux manjaro. The same code works fine when run in Windows 10/Visual Studio 2019.

The crash happens at the startup when trying to resolve context migrations contextInstance.Database.Migrate();

To Reproduce

Class invoking the exception
class DbContextsMigrator
    {
        public void MigrateDatabase(IServiceProvider serviceProvider, string[] dependentAssemblies)
        {
            if (serviceProvider == null)
                throw new ArgumentNullException(nameof(serviceProvider));
            if (dependentAssemblies == null)
                throw new ArgumentNullException(nameof(dependentAssemblies));

            Assembly[] assemblies = LoadAssemblies(dependentAssemblies);

            Type[] dbContextTypes = assemblies.SelectMany(a => a.GetExportedTypes())
                .Where(t => typeof(DbContext).IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract)
                .ToArray();

            foreach (Type eachDbContextType in dbContextTypes)
            {
                var genericDbContextOptionsType = typeof(DbContextOptions<>).MakeGenericType(eachDbContextType);

                object dbContextOptionsInstance = serviceProvider.GetService(genericDbContextOptionsType);

                using (DbContext contextInstance = (DbContext) Activator.CreateInstance(eachDbContextType, dbContextOptionsInstance))
                {
                    contextInstance.Database.Migrate();
                }
            }
        }

        private Assembly[] LoadAssemblies(string[] dependentAssemblies)
        {
            var assemblies = new Assembly[dependentAssemblies.Length];

            for (int i = 0; i < dependentAssemblies.Length; i++)
            {
                assemblies[i] = Assembly.Load(dependentAssemblies[i]);
            }

            return assemblies;
        }

Exceptions (if any)

System.PlatformNotSupportedException: Strings.PlatformNotSupported_DataSqlClient
warn: Microsoft.EntityFrameworkCore.Model.Validation[10400]
Sensitive data logging is enabled. Log entries and exception messages may include sensitive application data; this mode should only be enabled during development.
Application startup exception: System.PlatformNotSupportedException: Strings.PlatformNotSupported_DataSqlClient
   at Microsoft.Data.SqlClient.SqlConnection..ctor(String connectionString)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerConnection.CreateDbConnection()
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.get_DbConnection()
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.<>c__DisplayClass18_0.<Exists>b__0(DateTime giveUp)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.<>c__DisplayClass12_0`2.<Execute>b__0(DbContext c, TState s)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func`2 operation, Func`2 verifySucceeded)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.Exists(Boolean retryOnNotExists)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate(DatabaseFacade databaseFacade)
   at <Project>.Framework.Data.DbContextsMigrator.MigrateDatabase(IServiceProvider serviceProvider, String[] dependentAssemblies) in /<ProjectPath>/src/<Project>.Framework/Data/DbContextsMigrator.cs:line 31
   at <Project>.Framework.Environment.ApiStarter.EnsureDatabaseMigrations(IServiceProvider serviceProvider, String[] depdendentAssemblies) in /<ProjectPath>/src/<Project>.Framework/Environment/ApiStarter.cs:line 48
   at <Project>.WebApi.Startup.Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory, IHostApplicationLifetime appLifetime) in /<ProjectPath>/src/<Project>.WebApi/Startup.cs:line 251
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Span`1& arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
   at Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.<Build>b__0(IApplicationBuilder builder)
   at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
   at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.<Configure>g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
   at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.Hosting.WebHost.BuildApplication()
crit: Microsoft.AspNetCore.Hosting.Diagnostics[6]
      Application startup exception
      System.PlatformNotSupportedException: Strings.PlatformNotSupported_DataSqlClient
         at Microsoft.Data.SqlClient.SqlConnection..ctor(String connectionString)
         at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerConnection.CreateDbConnection()
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.get_DbConnection()
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
         at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.<>c__DisplayClass18_0.<Exists>b__0(DateTime giveUp)
         at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.<>c__DisplayClass12_0`2.<Execute>b__0(DbContext c, TState s)
         at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
         at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func`2 operation, Func`2 verifySucceeded)
         at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.Exists(Boolean retryOnNotExists)
         at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.Exists()
         at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
         at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
         at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate(DatabaseFacade databaseFacade)
         at <Project>.Framework.Data.DbContextsMigrator.MigrateDatabase(IServiceProvider serviceProvider, String[] dependentAssemblies) in /<ProjectPath>/src/<Project>.Framework/Data/DbContextsMigrator.cs:line 31
         at <Project>.Framework.Environment.ApiStarter.EnsureDatabaseMigrations(IServiceProvider serviceProvider, String[] depdendentAssemblies) in /<ProjectPath>/src/<Project>.Framework/Environment/ApiStarter.cs:line 48
         at <Project>.WebApi.Startup.Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory, IHostApplicationLifetime appLifetime) in /<ProjectPath>/src/<Project>.WebApi/Startup.cs:line 251
         at System.RuntimeMethodHandle.InvokeMethod(Object target, Span`1& arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
         at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
         at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
         at Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.<Build>b__0(IApplicationBuilder builder)
         at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
         at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.<Configure>g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
         at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
         at Microsoft.AspNetCore.Hosting.WebHost.BuildApplication()
Unhandled exception. System.PlatformNotSupportedException: Strings.PlatformNotSupported_DataSqlClient
   at Microsoft.Data.SqlClient.SqlConnection..ctor(String connectionString)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerConnection.CreateDbConnection()
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.get_DbConnection()
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.<>c__DisplayClass18_0.<Exists>b__0(DateTime giveUp)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.<>c__DisplayClass12_0`2.<Execute>b__0(DbContext c, TState s)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func`2 operation, Func`2 verifySucceeded)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.Exists(Boolean retryOnNotExists)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate(DatabaseFacade databaseFacade)
   at <Project>.Framework.Data.DbContextsMigrator.MigrateDatabase(IServiceProvider serviceProvider, String[] dependentAssemblies) in /<ProjectPath>/src/<Project>.Framework/Data/DbContextsMigrator.cs:line 31
   at <Project>.Framework.Environment.ApiStarter.EnsureDatabaseMigrations(IServiceProvider serviceProvider, String[] depdendentAssemblies) in /<ProjectPath>/src/<Project>.Framework/Environment/ApiStarter.cs:line 48
   at <Project>.WebApi.Startup.Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory, IHostApplicationLifetime appLifetime) in /<ProjectPath>/src/<Project>.WebApi/Startup.cs:line 251
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Span`1& arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
   at Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.<Build>b__0(IApplicationBuilder builder)
   at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
   at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.<Configure>g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
   at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.Hosting.WebHost.BuildApplication()
   at Microsoft.AspNetCore.Hosting.WebHost.StartAsync(CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token, String startupMessage)
   at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token, String startupMessage)
   at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token)
   at Microsoft.AspNetCore.Hosting.WebHostExtensions.Run(IWebHost host)
   at <Project>.WebApi.Program.Main(String[] args) in /<ProjectPath>/src/<Project>.WebApi/Program.cs:line 

Further technical details

  • ASP.NET Core version: 6.0.0.sdk100-2
  • The IDE: VS Code (linux snap)
dotnet --info Output
.NET SDK (reflecting any global.json):
 Version:   6.0.100
 Commit:    9e8b04bbff

Runtime Environment:
 OS Name:     manjaro
 OS Version:  
 OS Platform: Linux
 RID:         arch-x64
 Base Path:   /usr/share/dotnet/sdk/6.0.100/

Host (useful for support):
  Version: 6.0.0
  Commit:  4822e3c3aa

.NET SDKs installed:
  2.1.818 [/usr/share/dotnet/sdk]
  3.1.120 [/usr/share/dotnet/sdk]
  6.0.100 [/usr/share/dotnet/sdk]

.NET runtimes installed:
  Microsoft.AspNetCore.App 6.0.0 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 2.1.30 [/usr/share/dotnet/shared/Microsoft.NETCore.App]
  Microsoft.NETCore.App 3.1.20 [/usr/share/dotnet/shared/Microsoft.NETCore.App]
  Microsoft.NETCore.App 6.0.0 [/usr/share/dotnet/shared/Microsoft.NETCore.App]

To install additional .NET runtimes or SDKs:
  https://aka.ms/dotnet-download

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 2
  • Comments: 22 (6 by maintainers)

Most upvoted comments

@JRahnama & @DFDark - I completely uninstalled the dotnet SDK and ASPNet runtimes that I had previously installed via the Arch User Repository, and installed the SDK via the official install script:

curl -sSL https://dot.net/v1/dotnet-install.sh | sudo bash /dev/stdin -c LTS --install-dir /usr/share/dotnet
sudo ln -sf /usr/share/dotnet/dotnet /usr/bin/dotnet

dotnet --list-sdks
# 6.0.101 [/usr/share/dotnet/sdk]

dotnet --list-runtimes
# Microsoft.AspNetCore.App 6.0.1 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
# Microsoft.NETCore.App 6.0.1 [/usr/share/dotnet/shared/Microsoft.NETCore.App]

The version on the AUR seems to be outdated - 6.0.100. This has fixed the problem for me, at least on my Linux ARM64 machine.

EDIT:

Also tested this on my AMD64 machine - problem solved with v6.0.101 😃

I’ve just encountered this problem again. Oddly enough, running the program with dotnet run --arch x64 --os linux works. However, I could not get the debugger in vs code to work to work with this, so ultimately the previous above solution had to be done again. I don’t know why this should have worked though.

The above advice by @ConductorPete did not work for me until I totally removed the microsoft.data.sqlclient folder in the nuget directory. Below is a reproduction of my exact steps on Manjaro Linux.

  1. Remove the sdks and runtimes.

Either do sudo pacman -R dotnet-sdk to remove the sdk, or do:

sudo rm -R /usr/share/dotnet/sdk/6*
sudo rm -R /usr/share/dotnet/shared/Microsoft.AspNetCore.App/6*
sudo rm -R /usr/share/dotnet/shared/Microsoft.NETCore.App/6*
  1. Remove the nuget package.

sudo rm -R ~/.nuget/packages/microsoft.data.sqlclient

  1. Follow the steps of @ConductorPete, reproduced below.
curl -sSL https://dot.net/v1/dotnet-install.sh | sudo bash /dev/stdin -c LTS --install-dir /usr/share/dotnet
sudo ln -sf /usr/share/dotnet/dotnet /usr/bin/dotnet

For me, it is a problem. I agree with you, we shouldn’t have to copy the file manually… the solution I used only solves it temporarily, I hope this problem will be fixed soon

I was having a similar issue using PopOs, my app was running normally on Windows, but on Linux I got this message when I ran . After much searching, I found a solution that solved my problem on a Google forum (https://groups.google.com/g/exceldna/c/4PQLjPj76N4/m/w-0kVCYVDAAJ).

I added the following instructions in my csproj:

    <Target Name="PostBuild" AfterTargets="PostBuildEvent">
         <Exec Command="cp $(OutDir)runtimes/unix/lib/netcoreapp3.1/Microsoft.Data.SqlClient.dll $(OutDir)" />
       </Target>

And it worked! I am using .net 6, entity framework 6.0.9

See-also: https://github.com/dotnet/SqlClient/issues/1423 (seems like the same issue, but that one is still open, so perhaps it’s more likely to be noticed)

It’s a problem that I’m getting here too. I already had it working on Ubuntu 22.04 LTS, but something happened after a system update. Running with dotnet run --arch x64 --os linux works, but its not a solution, nor even a workaround (at least in a development environment). Tried to clean the environment and install the latest .NET 6 (6.0.108), event with the new dotnet6 package of APT, but the result is the same.

@JRahnama I migrated to a docker image, which uses version .101 and the problem went away, so it’s doubly confirmed that this was a version .100 bug.

I’m getting the same on both Artix x86 (Arch Linux without SystemD/with OpenRC) and Arch Linux arm64. Manjaro Linux (@DFDark 's OS) is also Arch Linux-based.

I am constructing the connection string like this:

                        var connectionStringBuilder = new SqlConnectionStringBuilder
			{
				DataSource = $"{HostName},{HostPort}",
				InitialCatalog = DatabaseName,
				UserID = UserId,
				Password = Password
			};

			return connectionStringBuilder.ConnectionString;