无法将null值分配给System.DateTime类型的成员

use*_*034 3 linq-to-sql asp.net-mvc-3

我有例外:

The null value cannot be assigned to a member with type System.DateTime which is a non-nullable value type. 
Source Error: 
var bd = (from d in baza.hpurs where d.userID == userID && d.date !=null select d.date).Max();
Run Code Online (Sandbox Code Playgroud)

我的方法:

 public ActionResult Add_hours(int userID)
    {
        var dat = DateTime.Today;

        var bd = (from d in baza.hours where d.userID == userID && d.date !=null select d.date).Max();

        if (bd != dat)
        {
            return View();
        }

     else
    {
        var dd = (from d in baza.hours where d.userID == userID && d.date == dat select d.hoursID).Single();
        return RedirectToAction("hours_is", "Employer", new { HoursID = dd });
    }
}
Run Code Online (Sandbox Code Playgroud)

它工作得很好,但只有当我在具体用户的小时表中有1个或更多数据时.这个错误是我希望在具体用户没有添加任何小时的表中添加小时数.我不知道如何解决它...

And*_*bel 8

这是LINQ to SQL漏洞抽象的要点之一.Max()C#中函数的语义是,InvalidOperationException如果序列中没有元素,则抛出一个.SQL MAX()函数的语义是返回NULL.C#代码编译好像遵循C#语义,但代码永远不会作为C#代码执行.它被翻译成SQL语义规则的SQL.

要处理这个问题,您需要在没有匹配元素时决定您想要什么.如果你想要一个null值,显式声明一个可以为null的变量并引入一个额外的强制转换DateTime?来告诉null可能返回的LINQ to SQL .

DateTime? bd = (from d in baza.hpurs 
                where d.userID == userID && d.date !=null 
                select (DateTime?)d.date).Max();
Run Code Online (Sandbox Code Playgroud)