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
类没有为 DateTime
和DateTime?
,但是带有 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/