Entity Framework Core Count inside Select

asp.net-core c# entity-framework-core linq

Question

I have created a method that filters my dataset. I also created another method that counts the amount of items there are with the filters applied. This method looks like this:

return new Count
        {
            Address = this.Filter(/* paramters to filter */)
                .GroupBy(person => person.Address.City)
                .Select(group => new Amount<string>
                {
                    Type = group.Key /* so the city */,
                    Count = group.Count()
                }),
        };

Count has a couple of lists of amount objects. The amount objects holds the name of what it will filter on and a count of how many the filter contains.

this.Filter()

Is a private method that will return an IQueryable from the DbContext.

Everything works, however, it is very slow with a large amount of data. The reason for this is that the GroupBy() and the Count() could not be translated and will be evaluated locally. It gives the following warnings:

warn: Microsoft.EntityFrameworkCore.Query[20500]
      The LINQ expression 'GroupBy([entity.RequestRating], [entity])' could not be translated and will be evaluated locally.
warn: Microsoft.EntityFrameworkCore.Query[20500]
      The LINQ expression 'Count()' could not be translated and will be evaluated locally.
warn: Microsoft.EntityFrameworkCore.Query[20500]
      The LINQ expression 'Count()' could not be translated and will be evaluated locally.

What would be a better approach to this? This is a ASP.NET CORE project

1
0
1/9/2019 8:34:38 AM

Accepted Answer

Try this:

var amountList = Persons.Where(paramters to filter)
            .GroupBy(person => person.Address.City)
            .Select(group => new Amount()
            {
                City = group.Key,
                CityCount = group.Count()
            }).Tolist();
0
1/8/2019 4:47:14 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow