asp.net-mvc - 聚合 LINQ 查询中的 Entity Framework 对象限制

标签 asp.net-mvc linq entity-framework anonymous-types

我有一个相当复杂的查询,我想返回一些特定的类型。主要涉及日期/时间计算或字符串值,当我尝试除 System.DateTime 类型之外的任何内容时, Entity Framework 似乎在吐槽:

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

有问题的查询是:

    // Here comes the aggregate query.
    object summary = from te in ctx.TimeEntries
                     where te.StartTime >= startofweek
                     && te.UserName == User.Identity.Name
                     group te by te.StartTime.Day into Groups
                     select new
                     {
                         Key = Groups.Key,
                         Count = Groups.Count(),
                         //Total = Groups.Sum(n => (double)((n.EndTime ?? DateTime.Now) - n.StartTime).TotalMinutes / 60),
                         Tasks = from t in Groups
                                 orderby t.StartTime descending
                                 select new
                                 {
                                     Name = t.Task.TaskName,
                                     Project = t.Task.Batch.Project.ProjectName,
                                     Batch = t.Task.Batch.BatchName,
                                     //Minutes = ((t.EndTime ?? DateTime.Now) - t.StartTime).Minutes,
                                     Start = t.StartTime.Date,
                                     Stop = t.EndTime,
                                     Description = t.Notes,
                                     Breaks = t.BreakFor ?? 0
                                 }
                     };

在上面的查询中,属性“Start”将失败并出现上述错误。但是,如果我只是“Start = t.StartTime”,一切都会好起来的。同样,注释掉“Minutes”的值也会导致问题。

欢迎提出建议!

最佳答案

您只能在 L2E 查询中使用受支持的成员,并且 Date isn't one of those .

一种解决方法是将单个 L2E 查询分解为一个 L2E 查询,后接一个 LINQ to Objects 查询:

var q = from e in Context.Entities
        select new
        {
            Id = e.Id,
            DateTime = e.DateTime
        };

var r = from e in q.AsEnumerable()
        select new
        {
            Id = e.Id,
            Date = e.DateTime.Date
        };

关于asp.net-mvc - 聚合 LINQ 查询中的 Entity Framework 对象限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2264714/

相关文章:

javascript - 在 Javascript 中访问 Razor bool 变量时出错

c# - 从流式 XML 文件中解析并提取值?

asp.net-mvc - ASP.NET MVC OutputCache 不适用于根 URI

asp.net-mvc-3 - 使用存储库模式获取最后插入的行 ID

c# - 何时处置 HttpResponseMessage 或 HttpContent

asp.net-mvc - 将转换应用到 web.config 失败

c# - 为什么 LINQ (c#) 与 Seq (f#) 之间存在性能差异

Linq .Contains with large set 导致 TDS 错误

c# - 将一段代码更改为表达式

asp.net - 在 EntityDataSource 中插入新记录