Convert sql query into linq

122 Views Asked by At

How can i convert below sql query into linq?

SELECT
    COUNT(CASE WHEN P.Archived = '1' THEN 1  END) As ACount,
    COUNT(CASE WHEN P.IsImportant = '1' and P.Archived = '0' THEN 1  
END) As ICount,
    COUNT(CASE WHEN P.CreatedById = 1389 and P.Archived = '0' THEN 1 END) As CCount,
    COUNT(CASE WHEN P.CreatedById != 1389 and P.Archived = '0' THEN 1 END) As SCount,
    COUNT(*) as TotalThreatModelsCount
FROM Parties P
1

There are 1 best solutions below

2
On

This won't result in the same exact query, as it will result in 5 separate queries to the database, but it will give the same results.

    using (YourContext context = new YourContext())
    {
        int ACount = context.Parties.Count(_ => _.Archived == "1");
        int ICount = context.Parties.Count(_ => _.IsImportant == "1" &&  _.Archived == "0");
        int CCount = context.Parties.Count(_ => _.CreatedById == 1389 && _.Archived == "0");
        int SCount = context.Parties.Count(_ => _.CreatedById != 1389 && _.Archived == "0");
        int TotalThreadModelsCount = context.Parties.Count();
    }