“System.InvalidCastException"从SQL Server 2012 Express检索
本文关键字:Server SQL 2012 Express 检索 System InvalidCastException quot | 更新日期: 2023-09-27 18:03:48
我正在尝试测试一种方法,从SQL Server 2012 Express实例中检索一些信息并将其"添加"到列表中。问题是,当我试图运行测试时,我得到错误:
"系统。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()等方法也能达到同样的效果
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();
检查columns是否允许为空。如果是,则使类型为空,即
OwnerId = (int?)dr["owner_id"],