0

我正在开发我的第一个 MVC 应用程序并遇到了错误。

我正在尝试查询数据库并在视图页面上显示结果。

这是代码

 public class foreclosureList
{
    public string Area { get; set; }
    public int NumberOfListings { get; set; }
}
public class RETS_ListingsModel
{

    public RETS_ListingsModel(){} // empty COnstructor

    public static IEnumerable<foreclosureList> getForeclosureList() // making an IEnumerable list to contain the forclosure data
    {
        SqlConnection myConn;
        SqlCommand myCmd;
        SqlDataReader myReader;

            System.Collections.ArrayList aforclosureList = new System.Collections.ArrayList(); // create an array to hold data, later it will be converted to the ienumerable list. 
            string mySql =
             "Select [Area], count (*) as numberListings from listingTable" +
             " Where ForeclosureYN = 'Y'" +
             " AND Area <> ''" +
             " Group By Area";

            myConn = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
            myCmd = myConn.CreateCommand();
            myCmd.CommandText = mySql;
            myConn.Open();

            foreclosureList currentList = new foreclosureList(); // making an instance foreclosureList class and then adding the results from the query.

            myReader = myCmd.ExecuteReader();
            while (myReader.Read())
            {

                currentList.Area = (string)myReader["Area"];
                currentList.NumberOfListings = (int)myReader["NumberOfListings"];
                aforclosureList.Add(currentList); // adding the class object to the array
            }


            myReader.Close();
            myConn.Close();

            IEnumerable<foreclosureList> iforeclosureList = aforclosureList.Cast<foreclosureList>(); //converting the array back to the ienumerable list
            return iforeclosureList;
        }

    }

但我收到一条错误消息: System.IndexOutOfRangeException: NumberOfListings

同样在我的视图页面上,为了访问这些数据,我在第 1 行使用以下代码是否正确

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Foreclosure.Models.foreclosureList>" %>
4

1 回答 1

3

这就是问题:

string mySql =
"Select [Area], count (*) as numberListings from listingTable" 

...
currentList.NumberOfListings = (int)myReader["NumberOfListings"];

您不会获取任何名为NumberOfListings. 你取numberListings。他们不一样。

此外,您应该using为您的连接、语句和阅读器使用语句,更改您的代码以遵循 .NET 命名约定,停止使用ArrayListList<T>代之以)并可能转移到 LINQ 之类的东西而不是手动 SQL(这将避免此错误)。

于 2013-05-15T13:45:00.537 回答