从SQL Server Express读取数据时出错

时间:2018-08-28 15:50:25

标签: c# sql-server sql-server-express sqldatareader

我有一个非常简单的选择语句,但是我一生都看不出有什么问题。我OBV为帖子屏蔽了真实的数据库和服务器名称。

public List<Customer> CustomersGetAll()
{
        var customers = new List<Customer>();
        Customer customer;

        using (var command = new SqlCommand())
        {
            command.Connection = _connection;
            command.CommandText =
                " SELECT Id, Reference, Name, SupplierGln, GLN, UseCustomerProductCodes, IncludeBranchInvoices, RequireBuyerOrderNoAndDate, RequireQuantityOfTradedUnits, " + 
                "RequireQuantityOfTradedUnits, DefaultBranchCode FROM Customer ORDER BY Reference ";

            using (SqlDataReader reader =  command.ExecuteReader())
            {
                while (reader.Read())
                {
                    customer = new Customer();
                    customer.ID = (int)reader["Id"];
                    customer.Reference = (string)reader["reference"];
                    customer.Name = (string)reader["Name"];
                    customer.SupplierGLN = (string) reader["SupplierGLN"];
                    customer.GLN = (string)reader["GLN"];
                    customer.IncludeBranchInvoices = (bool)reader["IncludeBranchInvoices"];
                    customer.UseBuyerProductCodes = (bool)reader["UseCustomerProductCodes"];
                    customer.RequireBuyerOrderNoAndDate = (bool)reader["RequireBuyerOrderNoAndDate"];
                    customer.RequireReturnToSupplierNoForCredit = (bool)reader["RequireQuantityOfTradedUnits"];
                    customer.RequireQuantityOfTradedUnits = (bool)reader["RequireQuantityOfTradedUnits"];
                    customer.DefaultBranchCode = reader["DefaultBranchCode"] as string;

                    foreach (var productCode in CustomerProductCodesGetByCustomerID(customer.ID))
                    {
                        customer.ProductCodes.Add(productCode.Key, productCode.Value);
                    }

                    foreach (var branchCode in GetCustomerBranchCodes(customer.ID))
                    {
                        customer.BranchCodes.Add(branchCode.Key, branchCode.Value);
                    }

                    customers.Add(customer);
                }
            }
        }

        return customers.ToList();
 }

我正在使用SQL Server 2017 Express,并将以下内容作为我的连接字符串:

public DatabaseEngine(string databasePath)
{
        try
        {
            _connectionString = string.Format("Data Source={0};Initial Catalog={1};Integrated Security=True;MultipleActiveResultSets=True;", @"MACHINENAME\SQLEXPRESS2017", "DBNAME");

            _connection = new SqlConnection(_connectionString);

            _connection.Open();
        }
        catch
        {
            if (_connection != null)
            {
                _connection.Close();
                _connection = null;
            }

            throw;
        }
 }

这是引发以下错误的例程:

 /// </summary>
 private void LoadCustomers()
 {
    cboCustomers.Items.Clear();
   _customers = _database.CustomersGetAll();

   if (_customers != null)
   {
       foreach (Customer customer in _customers)
       {
          cboCustomers.Items.Add(customer);
        }
   }
 }

这一切正常,并且确实可以正常连接到数据库,但是出现以下错误,我已经尝试了以下操作

MultipleActiveResultSets=True;

哪个是建议的以下错误修复程序,但对我而言不是这样?

  

已经有一个与此命令关联的打开的DataReader,必须先关闭它。

enter image description here

编辑1 因此,我取消了上面的查询,在重新启动sql框的情况下,仍然遇到相同的错误,以防万一有东西被保留。

  public List<Customer> CustomersGetAll()
    {
        var customers = new List<Customer>();
        Customer customer;

        using (var connection = new SqlConnection(_connectionString))
        {


                string sql =
                    " SELECT Id, Reference, Name, SupplierGln, GLN, UseCustomerProductCodes, IncludeBranchInvoices, RequireBuyerOrderNoAndDate, RequireQuantityOfTradedUnits, " +
                    "RequireQuantityOfTradedUnits, DefaultBranchCode FROM Customer ORDER BY Reference ";

            using (var command = new SqlCommand(sql,connection))
            {
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        customer = new Customer();
                        customer.ID = (int)reader["Id"];
                        customer.Reference = (string)reader["reference"];
                        customer.Name = (string)reader["Name"];
                        customer.SupplierGLN = (string)reader["SupplierGLN"];
                        customer.GLN = (string)reader["GLN"];
                        customer.IncludeBranchInvoices = (bool)reader["IncludeBranchInvoices"];
                        customer.UseBuyerProductCodes = (bool)reader["UseCustomerProductCodes"];
                        customer.RequireBuyerOrderNoAndDate = (bool)reader["RequireBuyerOrderNoAndDate"];
                        customer.RequireReturnToSupplierNoForCredit = (bool)reader["RequireQuantityOfTradedUnits"];
                        customer.RequireQuantityOfTradedUnits = (bool)reader["RequireQuantityOfTradedUnits"];
                        customer.DefaultBranchCode = reader["DefaultBranchCode"] as string;

                        foreach (var productCode in CustomerProductCodesGetByCustomerID(customer.ID))
                        {
                            customer.ProductCodes.Add(productCode.Key, productCode.Value);
                        }

                        foreach (var branchCode in GetCustomerBranchCodes(customer.ID))
                        {
                            customer.BranchCodes.Add(branchCode.Key, branchCode.Value);
                        }

                        customers.Add(customer);
                    }
                }
            }
        }
        return customers.ToList();
    }

2 个答案:

答案 0 :(得分:2)

command.Connection = _connection;

不要这样做。完成当前部分后,应断开连接。

.NET将为您维护一个内部连接池,因此您不必担心每次打开新连接的成本。

实际上,如果您尝试使用同一连接两次而不关闭前一个连接,则会收到您看到的错误。

答案 1 :(得分:0)

类似的方法可能对您有用:

public List<Customer> CustomersGetAll()
{
    var customers = new List<Customer>();
    Customer customer;
    using (var connection = new SqlConnection(_connectionString))
    using (var command = new SqlCommand(connection))
    {
        // do work...

此外,您可以避免使用System.Data.Common命名空间和DbProviderFactory对数据提供者进行硬编码。