There exist two methods to turn SQL query into LINQ query that is written in C#, method syntax or query syntax. The following is the LINQ translation of your SQL query taking into account both strategies. This assumes that you have the requisite entity classes and a DbContext set up for the Entity Framework.
By Using method
var result = (from bp in context.BPs
join mbr in context.MbrBPs on bp.BPId equals mbr.BPId
join si in context.SIs on bp.BPId equals si.BPId into siGroup
from si in siGroup.DefaultIfEmpty()
join st in context.STs on si.STId equals st.STId
where bp.CountryId == 1 && bp.RegionId == 1 && mbr.MemberId == 1 && si.IsActive == 1
group si by new { st.Description, st.STId } into g
select new
{
g.Key.Description,
g.Key.STId,
Expr1 = g.Count(s => s != null) // Count only non-null SI
})
.Union(
from si in context.SIs
join st in context.STs on si.STId equals st.STId into siGroup2
from si in siGroup2.DefaultIfEmpty()
group si by new { si.STId, si.ST.Description } into g
select new
{
g.Key.Description,
g.Key.STId,
Expr1 = g.Count(s => s != null) // Count only non-null SI
}
).ToList();
By using Query
var result = (from bp in context.BPs
join mbr in context.MbrBPs on bp.BPId equals mbr.BPId
join si in context.SIs on bp.BPId equals si.BPId into siGroup
from si in siGroup.DefaultIfEmpty()
join st in context.STs on si.STId equals st.STId
where bp.CountryId == 1 && bp.RegionId == 1 && mbr.MemberId == 1 && si.IsActive == 1
group si by new { st.Description, st.STId } into g
select new
{
Description = g.Key.Description,
STId = g.Key.STId,
Expr1 = g.Count(s => s != null) // Count only non-null SI
})
.Union(
from si in context.SIs
join st in context.STs on si.STId equals st.STId into siGroup2
from si in siGroup2.DefaultIfEmpty()
group si by new { st.Description, st.STId } into g
select new
{
Description = g.Key.Description,
STId = g.Key.STId,
Expr1 = g.Count(s => s != null) // Count only non-null SI
}
).ToList();