Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implicitly convert type 'object' to 'System.DateTime'. An explicit conversion exists (are you missing a cast?)

Tags:

c#

sql

I am developing my first programm and am facing some problems please help me complete it I have this code in c#:

SqlDataReader dr = null;
dr = cmd.ExecuteReader();
if (dr.Read()) 
{
client_id = dr["clientid"].ToString();
surname = dr["surname"].ToString();
othername = dr["othername"].ToString();
gender = dr["gender"].ToString();
date_ofbirth = dr["dateofbirth"];
nationality = dr["nationality"].ToString();
//age = dr["Age"];
residential_address = dr["residentialaddress"].ToString();
postal_address = dr["postaladdress"].ToString();
contact_number = dr["telephonenumber"].ToString();
marital_status = dr["maritalstatus"].ToString();
spouse_name = dr["spousename"].ToString();
email = dr["email"].ToString();
occupation = dr["occupation"].ToString();
typeof_id = dr["typeofid"].ToString();
id_number = dr["idnumber"].ToString();
id_expirydate = dr["idexpirydate"];
remarks = dr["remarks"].ToString();
picture = dr["picture"].ToString();
return true;
cmd.CommandText = null;
}

and the error message for this is ............... date_ofbirth = dr["dateofbirth"];

Error 2 Cannot implicitly convert type 'object' to 'System.DateTime'. An explicit conversion exists

(are you missing a cast?)

C:\Users\MICKY\Documents\Visual Studio 2008\Projects\Godswill\Godswill\Personal.cs 249 28 Godswill

like image 967
micky Avatar asked Jul 21 '11 07:07

micky


1 Answers

You should cast all of those, rather than blindly using ToString():

date_ofbirth = (DateTime) dr["dateofbirth"];

This will "unbox" the value as needed.

Of course, an easier approach here is to use an ORM or micro-ORM (such as "dapper") - then you just run:

var user = connection.Query<User>("select * from Users where Id=@id",
         new {id = 123}).First(); // (this is using "dapper")

where User is a class with properties that match the table definition, i.e.

public class User {
    public string Surname {get;set;}
    ...
    public DateTime DateOfBirth {get;set;}
}

Also; make sure you read about using here, i.e.

using(SqlDataReader dr = cmd.ExecuteReader())
{
    if (dr.Read()) {...etc...}
}

this is even more important for connections etc, but it acts to ensure the resource is correctly Dispose()d even if there is an error. This replaces your "init as null, set to null at the end" code, and has the advantage of actually doing something ;p

like image 129
Marc Gravell Avatar answered Oct 04 '22 00:10

Marc Gravell