正确使用DBNull

use*_*341 2 c# linq sql-server-2008 asp.net-mvc-3

有人可以告诉我DBNull的正确用法吗?我正在开发一个MVC3项目,它在控制器中有这个查询.

我有一个linq查询返回一个我知道第一个循环没有值的字段:

var qryGetBirthdate = (from c in db.Customer
                              select new
                                   {
                                      c.Birthdate
                                   }
                              ).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

在数据库中,Birthdate是Datetime类型,为null.

我为此做的检查是错误的:

 if ( !DBNull.Value.Equals(qryGetBirthdate.Birthdate))
           {
               DateTime? dob = qryGetBirthdate.Birthdate;
           }
Run Code Online (Sandbox Code Playgroud)

我尝试过其他博客的变体,但找不到答案.基本上我想要的是抓住'qryGetBirthdate.Birthdate'尚不存在的事实.我得到的只是对象没有设置为我知道的引用的例外.

我究竟做错了什么?

Tim*_*ter 6

FirstOrDefaultnull如果序列为空,则返回引用类型.这就是NullRefernceExceptionat 的原因qryGetBirthdate.Birthdate.所以检查它是否为空:

if(qryGetBirthdate != null)
{
    // now you can access it safely
}
Run Code Online (Sandbox Code Playgroud)

但是,您不需要创建匿名类型.

DateTime? firstBirthdate = (from c in db.Customer 
                             select c.Birthdate).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)