简体   繁体   English

LINQ to SQL lambda,其中[可为空的对象必须具有值错误]

[英]LINQ to SQL lambda where [nullable object must have a value error]

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? 另外,如何调试此函数lambda? When I hover over the x's, It shows no value. 当我将鼠标悬停在x上时,它没有显示任何值。 When when I try to print in the immediate window, it says "the name 'x' does not exist in the current context" 当我尝试在即时窗口中打印时,它说“名称“ x”在当前上下文中不存在”

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 . 在数据库中, 任何地方都没有null值。 Oh, and it doesn't go to the else, in the if/else block. 哦,在if / else块中,它不会进入其他。

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?). context.Datas很有可能为空,或者Data的任何userId都可以为null或x.Time为null,并且您尝试将其强制转换为(DateTime)而不是(DateTime?)。

You will have to add conditions to capture these null values in your assignment statement something like: 您将必须添加条件以在您的赋值语句中捕获这些空值,例如:

DateTime? datevalue = context.Datas == null
    ? null
    : (DateTime?)context.Datas.Where(x => x.UserId != null && x.UserID.Equals(userId))
                              .Min(x => x.Time);

If it is possible for firstRecordDate to be null, the .Min isn't allowed. 如果firstRecordDate可能为null,则不允许使用.Min。

Can you try this? 你可以试试这个吗?

firstRecordDate = (DateTime)context.Datas.Where(x => x.UserID.Equals(userId));
if (firstRecordDate.Count() > 0) firstRecordDate = firstRecordDate.Min(x => x.Time); 

if that works, then that's your problem. 如果可行,那就是您的问题。 There are probably more elegant ways to deal with this but at least you will have a workaround to start with. 可能有更优雅的方式来解决此问题,但至少您将有一个解决方法。

If you can be assured that at least one row has a valid time you could filter out the entries that have null as Time (or handle the case that DateTime.MaxValue is returned) 如果可以确定至少有一行具有有效时间,则可以过滤出时间为null的条目(或处理返回DateTime.MaxValue的情况)

firstRecordDate = context.Datas.Where(x => x.UserID == userId)
                               .Select( x=> x.Time ?? DateTime.MaxValue)
                               .Min();

Try 尝试

(DateTime)context.Datas.Where(x => x.UserId != null && x.UserID.Equals(userId)).Min(x => x.Time)

The userID != null should evaluate first which will prevent nulls when you get to the Min. userID!= null应该首先评估,这将在您到达Min时防止null。 I haven't tested that but I think I remember doing stuff like it in the past. 我还没有测试过,但是我想我记得以前做过类似的事情。

The Min function is attempting to return the minimum value, and I've encountered this message before when no elements were being returned from the IQueryable - you need to check for the existance of elements before invoking, or declare firstRecordDate as a DateTime? Min函数正在尝试返回最小值,在从IQueryable不返回任何元素之前,我遇到过此消息-您需要在调用之前检查元素是否存在,或者将firstRecordDate声明为DateTime? .

Debugging lambda's is not supported in the watch window. 监视窗口不支持调试lambda。 If you want to debug it, I would suggest instead making it a long form lambda over multi line in order to debug 如果您想调试它,我建议改用多行形式的长格式lambda进行调试

.Where(x =>
   {
       return x.ToString();
   });

You would be able to debug the inner method code then. 然后,您将能够调试内部方法代码。

You will get that error if context.Datas.Where(x => x.UserID.Equals(userId)) does not return any values. 如果context.Datas.Where(x => x.UserID.Equals(userId))不返回任何值,则会出现该错误。

If you use DateTime? 如果使用DateTime? instead of DateTime it will avoid this error by returning null. 而不是DateTime,它将通过返回null来避免此错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM