Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to SQL Left Join, Order and Group By Count

I've this query working perfectly:

SELECT B.ID, B.NAME, COUNT(BU.ID) AS TOTAL
FROM Building B
LEFT JOIN BuildingUser BU ON BU.ID_BUILDING = B.ID    
GROUP BY B.ID, B.NAME
ORDER BY COUNT(BU.ID) DESC, B.NAME

However I'm not getting the expected result when I convert it to Linq. It's returning count = 1 when left join returns null. So, I've been trying out this query:

var list1 = (from building in db.GetTable<Building>()
             join entitybuildinguser in db.GetTable<BuildingUser>()
                 on building.ID equals entitybuildinguser.ID_BUILDING into tmpbuildinguser
                 from buildinguser in tmpbuildinguser.DefaultIfEmpty()                 
             group building by new
             {
                 building.ID,
                 building.NAME
             } into grpBuilding                                                
             orderby grpBuilding.Select(g => g.ID).Count() descending, grpBuilding.Key.NAME
             select new
             {
                 ID_BUILDING = grpBuilding.Key.ID,
                 NAME = grpBuilding.Key.NAME,
                 users = grpBuilding.Select(g => g.ID).Count()
             });
like image 930
Gandarez Avatar asked Jul 30 '13 20:07

Gandarez


1 Answers

Try this:

from b in db.Buildings
join u in db.BuildingUsers on b.ID equals u.ID_BUILDING into g
orderby g.Count() descending, b.Name descending
select new 
{
    Id = b.ID,
    Name = b.NAME,
    Total = g.Count()
}
like image 161
Eren Ersönmez Avatar answered Oct 18 '22 10:10

Eren Ersönmez