Entity Framework object limitations in aggregate LINQ query

人盡茶涼 提交于 2019-12-31 03:32:12

问题


I have a rather complicated query that I'd like to have return some particular types. Mostly concerning date / time calculations or string values, the Entity Framework seems to be spitting the dummy when I try anything further than a System.DateTime type:

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

The query in question is:

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

In the query above, the property "Start" will fail with the aforementioned error. However, if I simply have "Start = t.StartTime" everything will be fine. Similarly, the commented out value for "Minutes" will also cause problems.

Suggestions most welcome!


回答1:


You can only use supported members in L2E queries, and Date isn't one of those.

One workaround is to break your single L2E query into one L2E query followed by one LINQ to Objects query:

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


来源:https://stackoverflow.com/questions/2264714/entity-framework-object-limitations-in-aggregate-linq-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!