asp.net-mvc-3 - 不能将 null 值分配给 System.DateTime 类型的成员

标签 asp.net-mvc-3 linq-to-sql

我有异常(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/

相关文章:

asp.net-mvc-3 - 在 MVC3 中使用 WebApi

.net - Column.DbType 影响运行时行为

c# - LINQ/Projection - 包含用于过滤的所有通配符

c# - 从 LINQ to SQL 升级到 EF 4.1 时如何最大限度地减少性能损失?

linq - 如何将用户表正确连接到成员资格表,或者您是否应该这样做?

asp.net - 如果关键服务不可用,如何使 ASP.NET 站点脱机

jquery - 如何在 ASP.NET MVC 3 和 JQuery 中基于单选按钮选择验证文本框?

linq-to-sql - 如何在 Linq to SQL 导航属性生成的查询中使用左连接而不是内连接

c# - 无法将类型 'System.Linq.IQueryable<Database.Table>' 隐式转换为 'bool'

c# - 表单验证只允许英文字母字符