Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group Multiple Tables in LINQ

I have a very simple SQL query:

SELECT r.SpaceID, Count (*), SpaceCode 
FROM Rider r JOIN Spaces s 
ON r.SpaceID = s.SpaceID
GROUP BY r.SpaceID, s.SpaceCode 

Please note that my group by clause is on multiple tables, I want to do the same in LINQ, I know how to group single table, but about multiple tables I have no idea.

like image 692
Manvinder Avatar asked Jan 04 '12 09:01

Manvinder


2 Answers

For grouping multiple tables you can do as:

group new { r,s } by new { r.SpaceID, s.SpaceCode }
like image 50
Pankaj Tiwari Avatar answered Sep 24 '22 18:09

Pankaj Tiwari


this might help:

(
    from r in db.Rider
    join s in db.Spaces
        on r.SpaceID equals s.SpaceID
    group new { r,s } by new { r.SpaceID, s.SpaceCode }
    into grp
    select new
    {
        Count=grp.Count(),
        grp.Key.SpaceID,
        grp.Key.SpaceCode
    }
)

Where db is the database context

like image 31
Arion Avatar answered Sep 22 '22 18:09

Arion