C#类System.Data.SqlClient无法加载文件或程序集

时间:2018-11-11 16:47:32

标签: c#

如何在.NET Standard 2.0中使用SqlClient指令?

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

在运行Visual Studio的那一刻,我遇到了很大的困难,遇到以下例外:

System.IO.FileNotFoundException: 'Could not load file or assembly 'System.Data.SqlClient, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.'

导致应用程序未运行,该指令已通过NuGet安装,我的类.csproj如下:

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

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="System.Data.SqlClient" Version="4.5.1" />
  </ItemGroup>

</Project>

窗体的框架设置为.NET Framework 4.6.1 ... 我无法更改类框架以使其匹配,并且我不确定这是否导致错误?

导致错误的方法-从类中引用:

//Connect to Database
    public void Connection()
    {
        try
        {
            // Create SqlConnection
            connString = "Data Source = xx; Initial Catalog = xx; User ID = xx; Password = xx";
            con = new SqlConnection(connString);
            con.Open();
        }
        catch (Exception ex)
        {
            string error;
            error = ex.ToString();
        }
    }

1 个答案:

答案 0 :(得分:1)

选项1)您可能已经尝试过了。 删除引用并手动添加。

选项2)输出或构建文件夹中的System.Data.SqlClient dll丢失 因此,尝试添加构建后脚本。

<Target Name="PostBuild" AfterTargets="PostBuildEvent">
    <Exec Command="copy ..\..\..\packages\System.Data.SqlClient\runtimes\win\lib\netstandard2.0\System.Data.SqlClient.dll bin\Debug\appname\" Condition="'$(IsWindows)' == 'true'" />
    <Exec Command="cp ../../../packages/System.Data.SqlClient/runtimes/unix/lib/netstandard2.0/System.Data.SqlClient.dll bin/Debug/appname/" Condition="'$(IsWindows)' != 'true'" />
</Target>