How to create Linq2Sql query that will group records from linked table and calculate 2 count fields

StackOverflow https://stackoverflow.com/questions/10203191

Question

Here I found how to join tables using Linq2Sql and count amount of linked records LINQ - Left Join, Group By, and Count

I've implemented it and it works ok for me: the following expression

var v = from c in db.GetTable<Country>()
        join t0 in db.GetTable<Team>() on c.Id equals t0.CountryId into t1
        from team in t1.DefaultIfEmpty()
        group team by c.Id into teamsGrouped
        select new CountryTeamsInfo
            {
                CountryId = teamsGrouped.Key,
                TeamsTotal = teamsGrouped.Count(),
                // TeamsWithoutOwnerFree = teamsGrouped.Count(t => t.OwnerId==0)
            }
            ;
         List<CountryTeamsInfo> res = v.ToList();

generates the following query:

SELECT c.Id, Count(*) as c1
FROM countries c
LEFT JOIN teams t1 ON c.Id = t1.Country
GROUP BY c.Id 

In fact I need also to count those linker records that has OwnerId field non-equal to 0.

It looks like I should just uncomment that line in linq expression (TeamsWithoutOwnerFree = teamsGrouped.Count(t => t.OwnerId==0)), but that doesn't work, attempt to execute that causes an error:

The given key was not present in the dictionary

The query don't come to SQL log file, and I can't examine it in the debugger.

What should be a proper way to count those lines from 'teams' table that meet additional criteria.

P.S. if it matters, I use C# 4.0, MySql 5.1 and BLToolkit 4.1

Was it helpful?

Solution 3

Here is query that works in my environment:

from c in db.GetTable<Country>()
where c.Allowed
select new CountryTeamsInfo
{
    CountryId = c.Id,
    TeamsTotal = db.GetTable<Team>().Count(t => t.CountryId == c.Id && t.Allowed),
    TeamsHasOwner = db.GetTable<Team>().Count(t => t.CountryId == c.Id && t.Allowed && t.OwnerId != 0),
}

Not the best solution (I need to repeat teams selection criteria t.Allowed in each sub-query), but still works well and generated SQL is good.

OTHER TIPS

Maybe try using GroupJoin() for your query:

var result = db.GetTable<Country>()
               .GroupJoin(db.GetTable<Team>(),
                   c => c.Id,
                   t => t.CountryId,
                   (country, teams) => new
                   {
                       CountryId = country.Id,
                       TeamsTotal = teams.Count(),
                       TeamsWithoutOwnerFree = teams.Count(t => t.OwnerId == 0)
                   })
               .ToList();

Due to RePierre help I was able to find the proper query:

var v = db.GetTable<Country>().Where(country => country.Allowed)
                    .GroupJoin(
                        db.GetTable<Team>(),
                        country => country.Id,
                        team => team.CountryId,
                        (country, teams) => new CountryTeamsInfo
                                                {
                                                    CountryId = country.Id,
                                                    TeamsTotal = teams.Count(),
                                                    TeamsWithoutOwnerFree = teams.Count(t => t.OwnerId != 0),
                                                }
                    ).GroupJoin(
                        db.GetTable<Team>().Where(te=>te.OwnerId==0),
                        cti => cti.CountryId,
                        team => team.CountryId,
                        (cti, teams) => new CountryTeamsInfo
                        {
                            CountryId = cti.CountryId,
                            TeamsTotal = cti.TeamsTotal,
                            TeamsWithoutOwnerFree = teams.Count(t => t.OwnerId != 0),
                        }
                    )
                    ;

My concern is it uses 2 sub-queries... will try to optimize that. Any ideas would be great

P.S. Actually, generated SQL query looks ugly as well:

SELECT
cti.Id as Id1,
cti.c1 as c11,
(
    SELECT
        Count(*)
    FROM
        teams te
    WHERE
        cti.Id = te.Country AND te.User = 0
) as c2
FROM
(
    SELECT
        country.Id,
        (
            SELECT
                Count(*)
            FROM
                teams t1
            WHERE
                country.Id = t1.Country
        ) as c1
    FROM
        countries country
    WHERE
        country.allow
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top