dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
14.67k stars 4.58k forks source link

System.Data.Odbc PlatformNotSupportedException #898

Open esso23 opened 4 years ago

esso23 commented 4 years ago

System.Data.Odbc v4.7.0 Platform: Windows Server 2019 version 1809 (build 17763.805) Runtime: .NET Core 3.1 (Library with odbc dependency is .NET Standard 2.1) Exception:

System.PlatformNotSupportedException: System.Data.ODBC is not supported on this platform.
   at System.Data.Odbc.OdbcConnection..ctor(String connectionString)
   at Connector.SysCfg.Odbc.OdbcSysCfgRepository..ctor(String dsnName) in D:\Sync\Repositories-Ipecon\paragon-platform\src\Connector.SysCfg\Odbc\OdbcSysCfgRepository.cs:line 28
...

Code:

mConnection = new OdbcConnection($"DSN={mDsnName};");

Additional info: Just migrated from .NET Framework 4.6.1 to .NET Core 3.1 on the same machine. OdbcConnection worked fine on .NET Framework 4.6.1. Application is x86.

esso23 commented 4 years ago

Ok, I figured out it was because of the .NET Standard, which is not supported. I still see some problems with this though: It's not the platform that is not supported. I was targeting win-x86 platform which is supported. I had to go to dotnet/corefx repo, check the System.Data.Odbc.csproj to find out what's going on. On this line:

<GeneratePlatformNotSupportedAssemblyMessage Condition="'$(TargetGroup)' == 'netstandard'">SR.Odbc_PlatformNotSupported</GeneratePlatformNotSupportedAssemblyMessage>

I think the exception is misleading and should be changed to something else.

ajcvickers commented 4 years ago

@esso23 Please attach a small, runnable project or post a small, runnable code listing that reproduces what you are seeing so that we can investigate.

ligf commented 4 years ago

I also encountered a similar problem The class library refers to odbc, and the console refers to the dll file, and it will prompt "System.Data.ODBC is not supported on this platform."

roji commented 3 years ago

This looks like it should no longer be relevant, as there won't be further versions of .NET Standard and libraries are expected to simply target .NET.

ActionNamou commented 3 years ago

Same issue here. I am new to c# and I was trying to make a connection to an sql table to fill a dataset like this

public static DataSet GetDataSetFromAdapter(DataSet dataSet, string connectionString, string queryString)
        {
            using (OdbcConnection connection =
                       new OdbcConnection(connectionString))
            {
                OdbcDataAdapter adapter =
                    new OdbcDataAdapter(queryString, connection);

                // Open the connection and fill the DataSet.
                try
                {
                    connection.Open();
                    adapter.Fill(dataSet);
                    MessageBox.Show("here u did it");

                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                // The connection is automatically closed when the
                // code exits the using block.
            }
            return dataSet;
        }

Please let me know how we can fix this error.

MicahKimel commented 1 year ago

I am also having this issue in .net5.0, my code is similar to @ActionNamou

roji commented 1 year ago

@ActionNamou @MicahKimel which .NET version (TFM) are you targetting? Can you please share your csproj file?

BryanCrotaz commented 1 year ago

I'm seeing this targeting .Net 6.0 (in the application and all the class libraries) and running as a service on a Windows 10 Pro VM

roji commented 1 year ago

Can you please share a minimal, runnable code sample - including your csproj?

MicahKimel commented 1 year ago

@roji Sure, here is an ASP.NET Core Web API template with TargetFramework netcoreapp3.1 with @ActionNamou code in the default controller. I didn't include my odbc connection string in the controller, but my connection string is valid and works fine in the Server Explorer. Thanks!

I get the error on the following line in the controller using (OdbcConnection connection = new OdbcConnection("my connection string"))

https://github.com/MicahKimel/SystemDataOdbcError

MaceWindu commented 1 year ago

@MicahKimel you should downgrade System.Data.Odbc to v6.0.1 https://github.com/dotnet/runtime/discussions/78550

MicahKimel commented 1 year ago

@MaceWindu Sweet Thanks!!

BryanCrotaz commented 1 year ago

6.0.1 gives the same error when the project is entirely built in .Net 6.0.

System.PlatformNotSupportedException: System.Data.ODBC is not supported on this platform.
   at System.Data.Odbc.OdbcCommand..ctor(String cmdText)
   at Signergy.Queries.Installations.GetUpdatedCrewQuery.Run(Int32 since, CancellationToken cancellationToken)
   at Signergy.Repositories.CrewRepository.GetCrewModifiedSince(Int32 modifiedSince, CancellationToken cancellationToken)
   at ServiceProcess.SignergyAgentProcess.QueryCrew(CancellationToken cancellationToken)
   at ServiceProcess.SignergyAgentProcess.LoopingQuery(CancellationToken token)
public class GetUpdatedCrewQuery : BaseQuery<IEnumerable<Installation>>
    {
        public GetUpdatedCrewQuery(IDBConnection db) : base(db)
        {
        }

        public async Task<ModifiedSinceResponse<CrewMember, int>> Run(int since, CancellationToken cancellationToken)
        {
            var command = new OdbcCommand(@"
                SELECT 
                    Installation_crew_members.INSTALLATION_CREW_MEMBERSID AS CrewId,
                    Installation_crew_members.STAFFID AS CrewStaffId,
                    Installation_crew_members.MemberName AS CrewName
                FROM
                    Installation_crew_members
                WHERE
                    CrewId > {Since}
                ORDER BY CrewId
            ");

            command.Connection = Connection;
            command.Parameters.AddWithValue("Since", since);

            Console.WriteLine("Querying crew since " + since);
            var reader = await command.ExecuteReaderAsync(CommandBehavior.SequentialAccess);

            var result = new List<CrewMember>();
            var lastModified = since;
            var columns = new OdbcReaderColumnCache(reader);

            while (reader.Read())
            {
                try
                {
                    var crewId = columns.ValueIntFor("CrewId");
                    var crewMember = new CrewMember(
                        id: crewId,
                        staffId: columns.ValueIntFor("CrewStaffId"),
                        name: columns.ValueStringFor("CrewName")
                    );
                    result.Add(crewMember);
                    if (crewId > lastModified)
                    {
                        lastModified = crewId;
                    }                        
                }
                catch (Exception e)
                {
                    Console.WriteLine("Skipping unreadable crew " + columns.ValueFor("CrewId") + ' ' + e.Message + ' ');
                }
            }

            return new ModifiedSinceResponse<CrewMember, int>(lastModified, result);
        }
    }

Library project file - Signergy.dll

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <Platforms>AnyCPU;x64</Platforms>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="System.Data.Odbc" Version="6.0.1" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\Models\Models.csproj" />
  </ItemGroup>

</Project>

App project file

<Project Sdk="Microsoft.NET.Sdk.Worker">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <UserSecretsId>dotnet-AgentWorkerService-2FBADBB8-2A06-47B2-A199-77A89EB9A91B</UserSecretsId>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
    <ProduceReferenceAssembly>False</ProduceReferenceAssembly>
    <AssemblyVersion>1.1</AssemblyVersion>
    <FileVersion>1.1</FileVersion>
    <Platforms>AnyCPU;x64</Platforms>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
    <PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
    <PackageReference Include="NetEscapades.Extensions.Logging.RollingFile" Version="2.4.1" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\ServiceProcess\ServiceProcess.csproj" />
    <ProjectReference Include="..\Signergy\Signergy.csproj" />
  </ItemGroup>
</Project>
BryanCrotaz commented 1 year ago

@roji what's wrong with the above app - why is it reporting this error whether running as a cmd line exe or as a service, on Windows 10?

I've tried with x86, Any CPU and x64 with version 7.0 and 6.0.1

roji commented 1 year ago

@BryanCrotaz and others, it will probably take me a few more days to look into this, thanks for your patience.

BryanCrotaz commented 1 year ago

@roji Emailed you source code in case that helps you diagnose. It fails immediately on startup

MaceWindu commented 1 year ago

@BryanCrotaz I don't know what exactly wrong with your code, but workers build produce runtimes sub-folder with runtime-specific builds. For some reason when you run your program it cannot locate proper runtime for windows and default files from build root used. And they contain netstandard2.0 version of odbc assembly, which always will throw such exception. You should check you don't remove/have windows runtime subfolder

chkrishna2001 commented 1 year ago

Is there a fix for this ?, I am getting this error when I use .net 5.0, but works when using .net 6.0

ajcvickers commented 1 year ago

@chkrishna2001 .NET 5 is out-of-support.

chkrishna2001 commented 1 year ago

@ajcvickers I know, but until we migrate, is there a work around to this ?

ajcvickers commented 1 year ago

I'm not aware of any workarounds.

gordon-matt commented 1 year ago

Just noticed this issue. Linking to one I recently opened myself: #88281

ActionNamou commented 9 months ago

Fixed this issue long ago but here is a little help for anyone new: Fix the issue by matching the System.Data.Odbc package version relative to the dotnet version you are on. Example, if you are on .net 5, go to System.Data.Odbc package and make sure you are also on one of the versions starting with 5.

donnyv commented 4 months ago

@ActionNamou That saved me. Thanks!