【发布时间】:2011-08-22 17:53:43
【问题描述】:
我收到了错误
[可为空的对象必须有值]
它指向代码的以下部分
.Min(x => x.Time)
这是整个函数。
public DateTime GetFirstRecord(long userId)
{
DateTime firstRecordDate;
using (DeviceExerciseDataDataContext context = new DeviceExerciseDataDataContext())
{
firstRecordDate = (DateTime)context.Datas.Where(x => x.UserID.Equals(userId)).Min(x => x.Time);
}
return firstRecordDate;
}
另外,我如何调试这个函数 lambda?当我将鼠标悬停在 x 上时,它没有显示任何价值。当我尝试在即时窗口中打印时,它说“名称'x'在当前上下文中不存在”
编辑:
So I've updated my code to this:
public DateTime? GetFirstRecord(long userId)
{
DateTime? firstRecordDate;
firstRecordDate = DateTime.Now;
using (DeviceExerciseDataDataContext context = new DeviceExerciseDataDataContext())
{
var test = context.Datas.Where(x => x.UserID.Equals(userId));
if (test != null)
firstRecordDate = (DateTime)test.Min(x => x.Time);
else
firstRecordDate = null;
}
return firstRecordDate;
}
但我仍然收到保存错误。
在数据库中,任何地方都没有空值。哦,它不会转到 if/else 块中的 else。
【问题讨论】:
-
要调试 lambda,您可以在 lambda 本身上放置一个断点,为此将光标放在 lambda 内并按 [F9],断点将位于 lambda 中而不是整行.
-
测试
test != null是没有意义的,因为test将只是从Where()子句返回的迭代器,而且肯定不会是null。能给我们看看模型吗?x.Time是DateTime还是Nullable<DateTime>?test.Count()的值是多少? -
@James Michael Hare:不能使用 Linq2SQL,除非你强制它先列出。
-
关于 Linq2SQL 的好消息
标签: c# .net linq-to-sql lambda