Search code examples
entity-framework-corelinq-to-objectsef-core-3.1ef-core-3.0ef-core-5.0

LINQ-to-Objects - cannot group by Object


I upgraded efcore 2.2 to 5 and simple group by is not working,
the data is already in memory, take a look:

List<IGrouping<Categories, Businesses>> businessesByCategory = 
    location.Businesses
            .GroupBy(x => x.Category.Parent ?? x.Category)
            .ToList();

In Ef Core 2.2 it worked fine, the businesses were grouped by their category, now it does nothing.

If I try to group by id it works:

List<IGrouping<int, Businesses>> businessesByCategory = location.Businesses
    .GroupBy(x => x.Category.ParentId ?? x.CategoryId)
   .ToList();

But I need the Category entity and this way I get only the category id.


Solution

  • The issue is caused by EF Core 3.0 no-tracking query behavior breaking change - No-tracking queries no longer perform identity resolution. Because of that, the Category objects with the same Id now are different instances, hence the default equality comparer used by LINQ to Objects GroupBy treats them as different keys, thus not grouping at all.

    EF Core 5.0 brings back the 2.x behavior - No-tracking queries with identity resolution, but you must opt-in for it using the AsNoTrackingWithIdentityResolution method in place of AsNoTracking(). Or QueryTrackingBehavior.NoTrackingWithIdentityResolution if setting the default ChangeTracker.QueryTrackingBehavior.