Pergunta

Please help me convert the MSSQL below to LINQ.

SELECT A.id, A.type, COUNT(IIf(B.BookId IS NOT NULL, 0, null)) AS TotalCount
FROM Store A
LEFT JOIN Book B ON A.id = B.id
GROUP BY A.id, A.type;

I currently have this LINQ code:

from a in Store
join b in Book on a.id equals b.id into c
from d in c.DefaultIfEmpty()
group a by new
{
    a.id,
    a.type
} into g 
select new
{
    StoreId = g.Key.id,
    StoreType = g.Key.type,
    TotalCount = g.Key !=null?g.Count():0
}

I think I'm missing something important.

Foi útil?

Solução

Since you're not trying to extract any values from the Book part of the join you don't need DefaultIfEmpty(), and since the join is a "group join" as a result of the into clause you don't need to group again:

from a in Store
join b in Book on a.id equals b.id into c
select new
{
    StoreId = a.id,
    StoreType = a.type,
    TotalCount = C.Count()
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top