在LINQ2SQL

时间:2015-11-30 15:38:11

标签: c# linq datetime linq-to-sql nullable

以下LINQ2SQL查询引发错误,指出它无法将null放入DateTime或更具体地

  

无法将null值分配给System.DateTime类型的成员,该类型是不可为空的值类型

这是代码,错误出现在LINQ行,即d = (from...行。

internal static DateTime? GetDateOfLastSkew(DateTime date, DateTime expiry)
{
    object d;
    using (SAFEX db = new SAFEX())
    {
        d = (from skew in db.Skew
             where skew.CalibrationDate.Date <= date.Date
                && skew.Expiry.Date == expiry.Date
             select skew.CalibrationDate).Max();
    }

    return d == DBNull.Value ? null : d as DateTime?;
}

dobject,因此无法为其分配null,这意味着它必须在LINQ查询内的某处发生。

我做错了什么?

2 个答案:

答案 0 :(得分:2)

当调用一组非可空类型(如DateTime)时,Max()将返回该非可空类型的值,或者如果集合中没有项目则抛出。

d可能是一个对象,但您尝试分配给它的唯一内容是DateTime,因此您唯一能够获得的就是DateTime或者DateTime?(您也可以取消装箱)。它永远不会被设置为DBNull.Value(在linq中几乎没有用,它主要用于直接处理数据库的较低级别)。

如果您知道总会有至少一个匹配的行,那么请忘记d并获取DateTime并在返回时将其转换为DateTime?

internal static DateTime? GetDateOfLastSkew(DateTime date, DateTime expiry)
{
  using (SAFEX db = new SAFEX())
  {
    return (from skew in db.Skew
         where skew.CalibrationDate.Date <= date.Date
            && skew.Expiry.Date == expiry.Date
         select skew.CalibrationDate).Max(); // Max returns a DateTime.
  }
}

如果你不知道那里总是至少有一个匹配,那么在selcet中转换为DateTime?,这样Max()现在正在处理一个可以为空的类型,在适当的时候可以返回null:

internal static DateTime? GetDateOfLastSkew(DateTime date, DateTime expiry)
{
  using (SAFEX db = new SAFEX())
  {
    return (from skew in db.Skew
         where skew.CalibrationDate.Date <= date.Date
            && skew.Expiry.Date == expiry.Date
         select (DateTime?)skew.CalibrationDate).Max(); // Max returns a DateTime or null on no matches.
  }
}

答案 1 :(得分:1)

将结果select转换为可为空:

d = (from skew in db.Skew
     where skew.CalibrationDate.Date <= date.Date
        && skew.Expiry.Date == expiry.Date
     select ((DateTime?)skew.CalibrationDate)).Max();

return d;