I’m getting the error
[nullable object must have a value]
And it’s point at the following part of the code
.Min(x => x.Time)
Here’s the whole function.
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;
}
Also, how can I debug this functions lambda? When I hover over the x’s, It shows no value. When when I try to print in the immediate window, it says “the name ‘x’ does not exist in the current context”
Edit:
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;
}
But I’m still getting the save error.
In the DB, There are no null value’s anywhere. Oh, and it doesn’t go to the else, in the if/else block.
There is a good chance that context.Datas could be null or any of the Data’s userId could be null or x.Time is null and you are trying to cast it as (DateTime) instead of (DateTime?).
You will have to add conditions to capture these null values in your assignment statement something like: