Saturday, May 14, 2022

EF Error : Unable to translate the given 'GroupBy' pattern. Call 'AsEnumerable' before 'GroupBy' to evaluate it client-side.

 I was trying out code from an article on c# corner  related to angular and web api. 

In one of the methods, there was a code like: 

        public IQueryable<Authors> GetAuthors()

        {

            return _dbContext.ArticleMatrices.GroupBy(author => author.AuthorId)

                  .Select(group =>

                        new Authors

                        {

                            AuthorId = group.FirstOrDefault().AuthorId,

                            Author = group.FirstOrDefault().Author,

                            Count = group.Count()

                        }).

                  .OrderBy(group => group.Author);

        }


This was a GET web api method so I tried calling it from browser. Suddenly I encountered following error : 

Unable to translate the given 'GroupBy' pattern. Call 'AsEnumerable' before 'GroupBy' to evaluate it client-side.


I found that the extension methods GroupBy , Select and OrderBy work on different input types. 

GroupBy works on IEnumerable 

Select works on  IEnumerable

But OrderBy works on IQueryable


GroupBy above gives error because _dbContext.EntityName returns IQueryable and GroupBy expects IEnumerable. 

Select works on IEnumberable so no issue for it. 

But OrderBy expects IQueryable ! 


Changing the above code as following worked: 


        public IQueryable<Authors> GetAuthors()

        {

            return _dbContext.ArticleMatrices.AsEnumerable().GroupBy(author => author.AuthorId)

                  .Select(group =>

                        new Authors

                        {

                            AuthorId = group.FirstOrDefault().AuthorId,

                            Author = group.FirstOrDefault().Author,

                            Count = group.Count()

                        }).AsQueryable()

                  .OrderBy(group => group.Author);

        }

No comments:

Post a Comment

 using Microsoft.AspNetCore.Mvc; using System.Xml.Linq; using System.Xml.XPath; //<table class="common-table medium js-table js-stre...