C# Invalid attempt to call Read when reader is closed

后端 未结 2 1387
梦谈多话
梦谈多话 2020-12-29 06:10

I am having Invalid attempt to call Read when reader is closed error when I am doing 3 tier project in C# language. What I am trying to do is retrieve address data column by

2条回答
  •  有刺的猬
    2020-12-29 06:20

    It doesn't work because you close the connection before returning the reader. Reader works only when the connection is open:

    result = command.ExecuteReader();
    connection.Close();
    
    return result; // here the reader is not valid
    

    Generally speaking, you should not be returning a reader to a business layer. Reader should be used only in the data access layer. It should be used and then it and the connection should be closed.

    You should rather return an object that can work after the connection is closed, e.g. a DataSet or DataTable or alternatively a collection of DTO's. For example:

    public List getDistributionAll()
    {
        List distributionAll = new List();
    
        using (var connection = new SqlConnection(FoodBankDB.GetConnectionString())) // get your connection string from the other class here
        {
            SqlCommand command = new SqlCommand("SELECT b.addressLineOne FROM dbo.Beneficiaries b INNER JOIN dbo.Distributions d ON d.beneficiary = b.id", connection);
            connection.Open();
            using (var dr = command.ExecuteReader())
            {
                while (dr.Read())
                {
                    string address = dr["addressLineOne"].ToString();
    
                    distributionAll.Add(new Distribution(address));
                }
            }
        }
    
        return distributionAll;
    }
    

提交回复
热议问题