Workaround needed for EF Core performing GroupBy operations in memory instead of in SQL

纵然是瞬间 提交于 2019-12-05 16:14:41

As @xanatos points out, this is is not supported in EF Core 1.1.0 (and not even 2.0.0). There is, however, a workaround, using literal SQL:

var q = db.MyTable
        .FromSql("select t.* from " +
                 "  (select distinct Field1 from MyTable) t0 " +
                 "cross apply " +
                 "  (select top 1 t.* from MyTable t " +
                 "  where t.Field1 = t0.Field1 " +
                 "  order by t.Field2 desc) t")                     
        .Select(t => new
        {
            t.Field1,
            MaxField2 = t.Field2
        })
        .ToList();

Not the solution I'd hoped for, but it works a charm.

Not supported in EF Core 1.1.0: https://github.com/aspnet/EntityFramework/issues/2341

LINQ's GroupBy() operators can sometimes be translated to SQL's GROUP BY clauses, in particular when aggregate functions are applied in the projection.

Sadly it won't be supported even in EF Core 2.0.0.

As you can see in this blog entry, GROUP BY will be supported in 2.1, which isn't released yet, but expected for Q1-Q2 2018 Q4 2017.

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