Web服务页面System.IndexOutOfRangeException

时间:2015-05-29 18:08:02

标签: asp.net asmx

public class GetAreaFromCity : System.Web.Services.WebService
{
    [WebMethod]
    public GetAreaByCityId ClassForGetCIty(int City_Id)
    {
        string CS =ConfigurationManager.ConnectionStrings["FOODINNConnectionString"].ConnectionString;

        using (SqlConnection con = new SqlConnection(CS))
        {
            SqlCommand cmd = new SqlCommand("spGetCityById",con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlParameter parameter = new SqlParameter("@ID", City_Id);

            //To assiate this parameter object with cmd object
            cmd.Parameters.Add(parameter);
            GetAreaByCityId GETAreaByCityId =new GetAreaByCityId();
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();

            //as WeakReference read data wewant ToString retrive Column value & then polute this property City_Id values
            while (reader.Read()){
                GETAreaByCityId.City_Id = Convert.ToInt32(reader["City_Id"]);
                GETAreaByCityId.Area_Id =     Convert.ToInt32(reader["Area_Id"]);

            }
            return GETAreaByCityId;

            //ToString return sql
        }
    }
}

这是我的服务页面代码

public class GetAreaByCityId
{
    public int Ca_Id {get;set; }
    public int City_Id { get; set; }
    public int Area_Id { get; set; }
}

这是按城市划分区域的等级

Create Proc [dbo].[spGetCityById]
@ID int 
as
Begin
Select Area_Id from 
CITIES_AREA where City_Id = @ID
End
GO

以及可以检索数据的数据库过程

  

System.IndexOutOfRangeException:City_Id   at System.Data.ProviderBase.FieldNameLookup.GetOrdinal(String fieldName)   at System.Data.SqlClient.SqlDataReader.GetOrdinal(String name)   at System.Data.SqlClient.SqlDataReader.get_Item(String name)   在WebApplication1.GetAreaFromCity.ClassForGetCIty(Int32 City_Id)中的c:\ Users \ Mudassir \ Documents \ Visual Studio 2013 \ Projects \ WebApplication1 \ WebAppli

以上错误我不知道问题是什么

1 个答案:

答案 0 :(得分:2)

您的存储过程仅返回Area_Id。 “while循环”while (reader.Read()){中的代码正在尝试从两列读取数据:

  • City_Id
  • Area_Id

您可以将列City_Id添加到存储过程查询的结果集中,但是您已经拥有该值,因为您将其作为参数传递给存储过程。

最简单的修复可能只是改变这一行:

GETAreaByCityId.City_Id = Convert.ToInt32(reader["City_Id"]);

到此:

GETAreaByCityId.City_Id = City_Id;

相关问题