简体   繁体   中英

“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. The problem is that when I try to run the test I get the error:

"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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM