从数据库填充列表 - System.InvalidCastException

时间:2015-05-19 19:24:51

标签: c# sql-server

我有一个简单的类,我想从数据库中填充一个列表:

class Foreman
{
    public int ForeBadge { get; set; }
    public string ForeName { get; set; }
}

这是我应该返回Foreman对象列表的方法:

    static public List<Foreman> getForeman()
    {
        connectionString.DataSource = "server";
        connectionString.InitialCatalog = "db";
        connectionString.UserID = "tunnelld";
        connectionString.Password = "pw";

        string queryString = "SELECT * FROM [QTRAXAdmin].[vwQT_Foreman]";

        List<Foreman> list;
        // Creates a SQL connection
        using (var connection = new SqlConnection(connectionString.ToString()))
        {
            using (var command = new SqlCommand(queryString, connection))
            {
                connection.Open();
                using (var reader = command.ExecuteReader())
                {
                    list = new List<Foreman>();
                    while (reader.Read())
                        list.Add(new Foreman { ForeBadge = reader.GetInt32(0), ForeName = reader.GetString(1) });
                }
            }
            connection.Close();
            return list;
        }

该方法在list.Add(new Foreman { ForeBadge = reader.GetInt32(0), ForeName = reader.GetString(1) });

时出错

with:类型&#39; System.InvalidCastException&#39;的未处理异常发生在System.Data.dll

对我而言,我似乎正在使用正确的变量类型。我做错了什么?

2 个答案:

答案 0 :(得分:4)

尝试在查询中明确使用字段名称,以确保列按您认为的顺序返回。这是我看到的最可疑的事情。或者,您可以在using块中使用列名。当然,仔细检查数据库中的列定义。

答案 1 :(得分:0)

假设表列名是forebadge和forename,请替换:

string queryString = "SELECT * FROM [QTRAXAdmin].[vwQT_Foreman]";

使用:

string queryString = "SELECT FOREBADGE, FORENAME FROM [QTRAXAdmin].[vwQT_Foreman]";