简体   繁体   中英

Can't select properties after group by in linq query

I have two tables, Organization and ApplicationUser. The relationship between them is One to Many. That means one Organization can have multiple Users. Now I need to write a query to show some organization properties along with the total users for each organization. I am trying to write the query. But after GroupBy function whenever I try to fetch the Property nothing comes. Here is the query:

var lists = await (from org in _dbContext.Organizations.AsNoTracking()
                   join dept in _dbContext.Departments.AsNoTracking() on org.Id equals dept.OrganizationId into orgDeptTemp
                   from orgDept in orgDeptTemp.DefaultIfEmpty()
                   join user in _dbContext.ApplicationUsers.AsNoTracking() on org.Id equals user.OrganizationId into orgUserTemp
                   from orgUser in orgUserTemp.DefaultIfEmpty()
                   group org by org.Id into orgGroupTemp
                   select new OrganizationDto
                   {
                       OrganizationId = orgGroupTemp.Key,
                       OrganizationName = orgGroupTemp.Key.......,
                       TotalUsers = How to get the total user
                   })
                   .ToListAsync();

In SQL the only available columns after a GROUP BY are the group key and aggregated columns. You need to add them into the group by line. So for example, group by org id and name

assuming your model is set up correctly use navigation properties

var query = from org in _dbContext.Organizations
            where org.Departments.Any(d => d.Whatever)
            select new OrganizationDto
            {
                OrganizationId = org.Id,
                OrganizationName = org.Name,
                TotalUsers = org.Users.Count(),
            };
var list = await query.AsNoTracking().ToListAsync();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM