[英]“System.InvalidCastException” error when retrieving data from SQL Server 2012 Express
I am trying to test a method that retrieves some info from a SQL Server 2012 Express instance and "adds" it into a list. 我正在尝试测试一种从SQL Server 2012 Express实例检索一些信息并将其“添加”到列表中的方法。 The problem is that when I try to run the test I get the error:
问题是当我尝试运行测试时出现错误:
"System.InvalidCastException"
“ System.InvalidCastException”
Here is the code: 这是代码:
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;
EDIT: @Dan provided a working answer. 编辑:@丹提供了一个有效的答案。 Though using a Convert.ToInt/ToString() etc method did the trick as well.
尽管使用Convert.ToInt / ToString()等方法也能达到目的。
Check if columns allows null. 检查列是否允许为空。 If so, make the type nullable Ie
如果是这样,则将类型设置为可为空
OwnerId = (int?)dr["owner_id"],
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.