c# - 截断时间将列表转换为可为空

标签 c# asp.net linq

 public List<DateTime> CalorieDates(int patientId)
    {
        using (var db = new DbConn())
        {
            List<DateTime> query =
                db.Calories.Where(d => d.PatientId == patientId && d.FoodId != "initial" && d.DateOfEntry != null)
                    .Select(d => System.Data.Entity.DbFunctions.TruncateTime(d.DateOfEntry)).Distinct().ToList();

            return query;
        }

    }

为什么这会将我的列表转换为可为 null 的日期时间?

Error   CS0029  Cannot implicitly convert type 
'System.Collections.Generic.List<System.DateTime?>'
to 'System.Collections.Generic.List<System.DateTime>'   

我该如何防止这种情况发生?我不想要可为 null 的日期时间列表。

最佳答案

出于某些未知原因(可能是为了让查询提供者的生活更轻松),DbFunctions 类没有为 DateTimeDateTime?,但是带有 DateTime? 参数的单个方法可以处理这两种情况。但是,作为副作用,它会将表达式类型更改为 DateTime?,即使参数是 DateTime(就像您的情况一样)。

所以你需要更正它。一旦您知道您始终传递 DateTime(因此结果不能为 null),您可以简单地在末尾添加 .Value TruncateTime 调用,问题已解决。

.Select(d => System.Data.Entity.DbFunctions.TruncateTime(d.DateOfEntry).Value)

关于c# - 截断时间将列表转换为可为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36777030/

相关文章:

c# - Clipboard.GetData() 在不应该返回 null 时返回

c# - 如何在Web应用程序而不是C#中的Windows应用程序中创建sqlite文件

c# - 使用 .NET WebBrowser 控件显示需要 X509 证书的 HTML 内容

c# - 从列表中排除一个项目(按索引),并采取所有其他

c# - Android 警报管理器未在指定时间触发

c# - ASP 连接错误 : Incorrect syntax near the keyword 'User

asp.net - 将ascx存储在数据库中

javascript - 在进行更改之前保持提交按钮处于禁用状态

c# - 错误信息 "Operator ' .' cannot be applied to operand of type ' lambda expression '"when converting a method to Extension Method?

c# - 引用组合框中的值时 LINQ 查询出错