我試圖測試從SQL Server 2012 Express實例中檢索某些信息並將其「添加」到列表中的方法。問題是,當我嘗試運行測試,我得到的錯誤:當從SQL Server 2012 Express檢索數據時出現「System.InvalidCastException」錯誤
"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;
編輯: @丹提供一個工作的答案。儘管使用Convert.ToInt/ToString()等方法也有效。
可能的原因是在你的數據庫空。 –
這似乎是這種情況。 – SpirosMesa