Linq GroupBy 表达式引发 AnonymousType 异常

Linq GroupBy expression raises AnonymousType exception

我有一个查询 returns 我用来显示 table 个值的 IEnumerable

我想按模型的 DateTime 字段 (StartTime) 对 table 进行分组(使用 <H3/> 元素)。

我修改了模型以使用适当的泛型:

IEnumerable<IGrouping<DateTime, FooViewModel>> routes;

我通过 FromSQL 查询填充模型:

        routes = (IEnumerable<IGrouping<DateTime, FooViewModel>>)await _context.FooViewModels
            .FromSql(@"SELECT  ..."
            )
            .GroupBy(r => new { r.StartTime.Date })
            .ToListAsync();

虽然代码通过了设计时集合,但我在 运行 时收到错误:

Unable to cast object of type 'System.Collections.Generic.List`1[System.Linq.IGrouping`2[<>f__AnonymousType5`1[System.DateTime],FooViewModel]]' to type 'System.Collections.Generic.IEnumerable`1[System.Linq.IGrouping`2[System.DateTime,FooViewModel]]'.

我做错了什么?

正如错误试图告诉您的那样,您不能将匿名类型作为 DateTime.

传递

由于您的视图接受 DateTime 的分组,因此您需要将 DateTime lambda 传递给 GroupBy(),以便它具有相同的类型。