我有一个方法应返回带有计算列的匿名对象列表,如下所示:

        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.Data.Objects.SqlClient.SqlFunctions'上的指定方法'System.Nullable 1[System.Int32] DateDiff(System.String, System.Nullable 1 [System.DateTime],System.Nullable`1 [System.DateTime])'无法转换为LINQ实体存储表达式。

有什么想法我可能在这里做错了吗?

编辑:我也尝试了提到here提到的EntityFunctions类,但效果不佳。

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
    };

08-24 16:00
查看更多