首页 > 解决方案 > Linq GroupBy 表达式引发 AnonymousType 异常

问题描述

我有一个查询,它返回一个IEnumerable用于显示值表的查询。

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

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

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]]'.

我做错了什么?

标签: c#linqasp.net-core-mvcentity-framework-coreasp.net-core-2.0

解决方案


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

由于您的视图接受一组DateTimes,因此您需要传递一个DateTimelambda 以GroupBy()使其具有相同的类型。


推荐阅读