检查表中的DB Null

时间:2016-05-05 06:38:17

标签: c# sql asp.net-mvc

我从表中获取数据但是“DateOfBirth”#39;字段显示为null。 所以如果' DateOfBirth'是null我该如何跳过它?

  

EXCEPTION:无法将DBNull.Value强制转换为' System.DateTime'。请使用可空类型

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")
});

4 个答案:

答案 0 :(得分:1)

尝试以这种方式检查DBNull值:

0.5 1.0 0.5 1.0 1.5 3.0

如果值等于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") }); ,则设置DBNull.Value或您想要的任何内容。

答案 1 :(得分:0)

使用可空的DateTime; DateTime?。在StaffModel

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

然后在填写该模型时:

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")
});

答案 2 :(得分:0)

如果您的变量不是null类型,则需要指定DateTime.MinDate

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")
});

答案 3 :(得分:0)

您可以检查DBNull.Value

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