我有异常(exception):
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 个或多个数据时。 当我想向表中添加小时数而具体用户尚未添加任何小时数时,会出现此错误。 我不知道如何解决它......
最佳答案
这就是 LINQ to SQL 抽象存在漏洞的地方之一。 C# 中 Max()
函数的语义是,如果序列中没有元素,则抛出 InvalidOperationException
。 SQL 的MAX()
函数的语义是返回NULL
。 C# 代码的编译就像遵循 C# 语义一样,但代码永远不会作为 C# 代码执行。它被翻译成 SQL 语义规则的 SQL。
要解决这个问题,您需要在没有匹配元素时决定您想要什么。如果您想要一个 null
值,请显式声明一个可为 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();
关于asp.net-mvc-3 - 不能将 null 值分配给 System.DateTime 类型的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8278610/