已经有一个与此命令关联的开放DataReader必须先关闭 - WCF

时间:2015-02-04 18:37:27

标签: sql-server web-services wcf exception sqldatareader

我有一个在WCF服务函数中调用的函数,我在excute阅读器行的subcategoriesGenerator函数中得到上述异常 对于在第二个函数中创建的cmd而言,它不应该是与另一个完全不同的实例 我很困惑,我需要帮助蚂蚁建议吗?

public static List<Category> categoryGenerator(ref SqlConnection con)
    {
        Category category = null;
        List<Category> list = null;
        List<SubCategory> subcategoryList = null;
        string categoryName = null;
        string categoryLink = null;
        SqlCommand cmd = new SqlCommand("sp_categoriesgenerator", con);
        SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

        while(reader.Read())
        {
            categoryName = reader["CategoryName"].ToString();
            categoryLink = reader["CategorySEO"].ToString() + "/";
            subcategoryList = subcategoriesGenerator(ref con, Convert.ToInt32(reader["CategoryId"].ToString()));

            category.categoryName = categoryName;
            category.categoryLink = categoryLink;
            category.subcategories = subcategoryList;

            list.Add(category);

            category = null;
        }
        reader.Close();
        return list;
    }//end CategoryGenerator

  public static List<SubCategory> subcategoriesGenerator(ref SqlConnection con, int categoryId)
    {
        SubCategory subcategory = null;
        List<SubCategory> list = null;
        string SubCategoryName = null;
        string SubCategoryLink = null;
        SqlCommand cmd = new SqlCommand("sp_subcategoriesgenerator", con);
        cmd.Parameters.AddWithValue("@categoryID", categoryId);
        SqlDataReader reader = cmd.ExecuteReader();

        while(reader.Read())
        {
            SubCategoryName = reader["SubcategoryName"].ToString();
            SubCategoryLink = reader["CategorySEO"].ToString() + "/" + reader["SubcategorySEO"] + "/";
            subcategory.subcategoryName = SubCategoryName;
            subcategory.subcategoryLink = SubCategoryLink;
            list.Add(subcategory);
            subcategory = null;
        }
        reader.Close();

        return list;
    }// end subcategoriesGenerator

1 个答案:

答案 0 :(得分:1)

当您打开阅读器时,您无法打开连接中的其他阅读器。你必须提取函数调用&#34; subcategoriesGenerator&#34;在您的第一个while语句之外或创建第二个数据库连接。我更喜欢这个解决方案:

首先,收集所有类别 其次,遍历所有类别并查询子类别并将它们附加到您的类别对象