TechGuy
TechGuy

Reputation: 4560

Check DB Null in table

I get data from a table but the 'DateOfBirth' field is shown as null. So if 'DateOfBirth' is null how can I skip it?

EXCEPTION : Cannot cast DBNull.Value to type 'System.DateTime'. Please use a nullable type

var dd = dx.Tables[0].AsEnumerable().Select(x => new StaffModel
{
    userno = x.Field<string>("USERNO"),
    dateofbirth = x.Field<DateTime>("DATEOFBIRTH"), // This comes as a DB NULL.
    passportno = x.Field<String>("PASSPORTNO"),
    passportexp = x.Field<DateTime>("EXPDATE")
});

Upvotes: 1

Views: 70

Answers (4)

erikscandola
erikscandola

Reputation: 2936

Try to check for DBNull value in this way:

var dd = dx.Tables[0].AsEnumerable().Select(x => new StaffModel
{
    userno = x.Field<string>("USERNO"),
    dateofbirth = x["DATEOFBIRTH"] != DBNull.Value ? x.Field<DateTime>("DATEOFBIRTH") : DateTime.MinValue,
    passportno = x.Field<String>("PASSPORTNO"),
    passportexp = x.Field<DateTime>("EXPDATE")
});

If value is equal to DBNull.Value then set MinValue or whatever you want.

Upvotes: 1

Rahul Nikate
Rahul Nikate

Reputation: 6337

You need to assign DateTime.MinDate if your variable is not null type.

var dd = dx.Tables[0].AsEnumerable().Select(x => new StaffModel
{
    userno = x.Field<string>("USERNO"),
    dateofbirth = x.Field<DateTime>("DATEOFBIRTH") ?? DateTime.MinDate, 
    passportno = x.Field<String>("PASSPORTNO"),
    passportexp = x.Field<DateTime>("EXPDATE")
});

Upvotes: 0

You can check for DBNull.Value

object value = x.Field("DATEOFBIRTH");
if (value == DBNull.Value)
{
    // do something
}  
else
{
    // do something else
}

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

Use a nullable DateTime; DateTime?. In your StaffModel:

public class StaffModel
{
    public string userno { get; set; }
    public DateTime? dateofbirth { get; set; }
    public string passportno { get; set; }
    public DateTime passportexp { get; set; }
}

Then when filling that model:

var dd = dx.Tables[0].AsEnumerable().Select(x => new StaffModel
{
    userno = x.Field<string>("USERNO"),
    dateofbirth = x.Field<DateTime?>("DATEOFBIRTH"), // note the ?        
    passportno = x.Field<String>("PASSPORTNO"),
    passportexp = x.Field<DateTime>("EXPDATE")
});

Upvotes: 0

Related Questions