无法添加对System.Data的引用。*

时间:2019-08-12 09:19:37

标签: c# sql-server visual-studio

我的c#解决方案最初只有一个项目,而我在该项目中拥有UI,Business,DAL。我可以毫无问题地使用System.Data.SQLClientReader。现在,我将其分为3个项目:(UI,Business,DAL),其中Business和DAL是类库。

当我将鼠标悬停在DAL中的SqlConnection上并转到快速修复时,突然不得不使用NuGet安装它。完成此操作后,Visual Studio在后台不显示任何错误,然后启动程序。然后,我在业务层中收到此错误,在DAL中调用了crud类:

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

班级:

using System;
using System.Data.SqlClient;

namespace BornToMove.DAL {
    public class Crud {

        public Crud() { }

        public SqlDataReader Read(SqlCommand cmd) {
            return cmd.ExecuteReader();
        }

        public long Create(SqlCommand cmd) {
            return Convert.ToInt64(cmd.ExecuteScalar());
        }
    }
}

DbMove类(仅显示一种方法):

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

namespace BornToMove.DAL {
    public class DbMove : IDbMove {

        private Crud Crud { get; set; }

        public DbMove(Crud crud) {
            this.Crud = crud;
        }

        public Move GetMove(long id) {
            SqlConnection conn = null;
            try {
                conn = new MSSqlConn().GetConn();
                conn.Open();
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = "SELECT * FROM Move WHERE id=@id";
                SqlParameter idParam = new SqlParameter("@id", System.Data.SqlDbType.Int) {
                    Value = id
                };
                cmd.Parameters.Add(idParam);
                cmd.Prepare();
                SqlDataReader reader = this.Crud.Read(cmd);
                Move move = null;
                if (reader.Read()) {
                    move = new Move {
                        Id = (long)reader.GetInt32(0),
                        MoveName = reader.GetString(1),
                        MoveDescription = reader.GetString(2),
                        Rating = reader.GetInt32(3),
                        SweatRate = reader.GetInt32(4)
                    };
                }
                return move;
            } catch {
                return null;
            } finally {
                conn.Close();
            }
        }

为什么突然需要使用NuGet安装它?为什么这甚至行不通?

3 个答案:

答案 0 :(得分:0)

问题出在不同项目中的System.Data.SqlClient dll版本。您应该在多个项目中使用相同版本,或者通过在app.config中提及dependentAssembly重定向到较新版本

在您的情况下,System.Data.SqlClient dll仅应在DAL中引用,并从Business和UI中删除,因为在那里没有用。

System.Data.SqlClient namespace is available in Sytem.Data dll

答案 1 :(得分:0)

我在引用我使用 NuGet System.Data.SQLClient 构建的 DLL 的应用程序中遇到了类似问题 - 除非应用程序中还安装了相同的 NuGet 包,否则会出现上述错误。一旦我在应用程序项目中安装了 NuGet SQLClient 包,一切都很顺利。

我认为您的问题是您的业务层通过调用 DAL 导致错误,因为 NuGet SQLClient 包未安装在业务层或整个应用程序项目中。

希望有用,

皮肤

答案 2 :(得分:-1)

我通过制定新的解决方案来解决此问题,而不是使用类型库(.NET Standard)的DAL和业务层,而是使用类库(.NET Framework)。然后,我可以毫无问题地引用dll