我有一个方法应该返回一个匿名对象列表,其中包含这样一个计算列:
var tomorrow = DateTime.Today.AddDays(1);
return from t in this.Events
where (t.StartTime >= DateTime.Today && t.StartTime < tomorrow && t.EndTime.HasValue)
select new
{
Client = t.Activity.Project.Customer.Name,
Project = t.Activity.Project.Name,
Task = t.Activity.Task.Name,
Rate = t.Activity.Rate.Name,
StartTime = t.StartTime,
EndTime = t.EndTime.Value,
Hours = (System.Data.Objects.SqlClient.SqlFunctions.DateDiff("m", t.StartTime, t.EndTime.Value) / 60),
Description = t.Activity.Description
};
不幸的是,我从 DateDiff 函数中得到以下错误:
指定方法 'System.Nullable1[System.Int32] DateDiff(System.String, System.Nullable1[System.DateTime], System.Nullable`1[System. DateTime])' 类型 'System.Data.Objects.SqlClient.SqlFunctions' 无法转换为 LINQ to Entities 存储表达式。
知道我在这里做错了什么吗?
编辑:我还尝试了提到的 EntityFunctions 类 here , 但效果不佳。
Minutes = EntityFunctions.DiffMinutes(t.EndTime, t.StartTime),
请您参考如下方法:
[编辑]
Hours = (System.Data.Objects.SqlClient.SqlFunctions.DateDiff("mi", t.StartTime, t.EndTime.Value) / 60)
不支持 SQL CE。
Hours = ((TimeSpan)(t.EndTime.Value - t.StartTime)).TotalHours
抛出 DbArithmeticExpression 异常
因此,我认为您必须分两步完成。抓取你需要的数据,然后在内存中计算时间差。
var events = (from t in context.Events
where (t.StartTime >= DateTime.Today && t.StartTime < tomorrow && t.EndTime.HasValue)
select t).ToArray();
return from t in events
select new
{
...
Hours = (t.EndTime.Value - t.StartTime).TotalHours
};
