How to make GroupBy on a complex object using IQueryable

I am looking for a way to make GroupBy on a complex object, and not just on one property. The problem is that I want to do this on IQueryable , because getting all the data from the table in this case is a very bad idea.

We are using Entity Framework 6.1.

The class is as follows:

 public class Pin {
   public Guid Id {get;set;}
   public Guid PageId {get;set;} /* this is the foreign key to our Pages-table */
   public PageClass Page {get;set;} /* this is a relation */
 }

I need to report the time when a particular page was “pinned”, also printing the name of the page.

Now my code is as follows:

var pinnedPages = GetAll().GroupBy(x => x, comparer);

foreach (var pinnedPage in pinnedPages)
{
    var numberOfTimesPinned = pinnedPage.Count();
    var pin = pinnedPage.Key;

    //write a line to the report
 }

But if I group on the PageId page, it pinnedPage.Keyreturns Guid, obviously, while I need the whole object Pagefor my reporting needs.

, SQL, , .

+4
2
GetAll().GroupBy(x => x.pageId).Select(_ => new {key = _.Key, page = _.FirstOrDefault().Page, count = _.Count()});

pageId, , (pageId), PageClass

+1

, , , , ( ):

var pinnedPages = context.Pages
                         .Select(p => new
                                      {
                                          Page = p
                                          Pins = p.Pins.Count()
                                      });

foreach (var pinnedPage in pinnedPages)
{
    var numberOfTimesPinned = pinnedPage.Pins;
    var pin = pinnedPage.Page; 

    //write a line to the report
}

context.Pages, IQueryable. GetAll IEnumerable (, GroupBy ).

+1

Source: https://habr.com/ru/post/1680496/


All Articles