从SQL Server 2012 Express

时间:2015-07-21 22:53:58

标签: c# linq

我正在尝试测试从SQL Server 2012 Express实例中检索某些信息并将其“添加”到列表中的方法。问题是,当我尝试运行测试时,我得到错误:

  

“System.InvalidCastException”

以下是代码:

List<Reference> lst = new List<Reference>();
//DB Connections is a class instance that takes care of the
//connection with the db.
DBConnections db = new DBConnections(DbConfig.conStr);
db.UpdateCmd("SELECT * FROM freelancers_references");

SqlDataReader dr = db.ExecuteReader();

if (dr.HasRows) {
    lst = dr.Cast<IDataRecord>().Select(r =>
        new Reference {
            Id = (int)dr["id"],
            OwnerId = (int)dr["owner_id"],
            Name = (string)dr["name"],
            Active = (bool)dr["active"]
        }).ToList<Reference>();
}

dr.Close();
return lst;   

编辑: @Dan提供了一个有效的答案。虽然使用Convert.ToInt / ToString()等方法也可以做到这一点。

2 个答案:

答案 0 :(得分:0)

检查列是否允许为空。如果是这样,请将类型设为可为空的I.e。

OwnerId = (int?)dr["owner_id"],

答案 1 :(得分:0)

DBConnections db = new DBConnections(DbConfig.conStr);
db.UpdateCmd("SELECT * FROM freelancers_references");
SqlDataReader dr = db.ExecuteReader();
if (dr.HasRows) {
    lst = dr.OfType<IDataRecord>().Select(r =>
        new Reference {
            Id = (int)dr["id"],
            OwnerId = (int)dr["owner_id"],
            Name = (string)dr["name"],
            Active = (bool)dr["active"]
        }).ToList();
}
dr.Close();