2011-11-26 75 views
2

我有例外:空值不能被分配到一个成员类型的System.DateTime

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(); 

我的方法:

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

它的工作原理很好,但只有当我有1个或多个以小时表格为具体用户的数据。 这个错误是当我想添加几小时到具体用户没有添加任何小时的表格。 我没有任何想法如何修复它...

回答

7

这是LINQ to SQL是漏洞抽象的一点。如果在序列中没有元素,C#中Max()函数的语义是抛出InvalidOperationException。 SQL的MAX()函数的语义是返回NULL。 C#代码编译好像遵循C#语义,但代码从未作为C#代码执行。它被转换为SQL语义规则所在的SQL。

要处理此问题,您需要在没有匹配元素时决定想要的内容。如果你想要一个null值,显式声明一个可为空的变量并引入一个额外的转换到DateTime?告诉LINQ to SQL可能返回null

DateTime? bd = (from d in baza.hpurs 
       where d.userID == userID && d.date !=null 
       select (DateTime?)d.date).Max(); 
+0

非常感谢。是工作。 – user1031034

+0

非常感谢你 –

+0

感谢您的解释,让我有点疯狂,试图找到愚蠢的解决方法。 – Yablargo

-1

问题很可能在:d.date!= null ...因为日期不能为空。另一种选择是使其可以为空(使用'?'类型的后缀)或使用类似DateTime.MinValue的东西。

相关问题