我不得不修改查詢以添加額外的聯接以引入分區名稱。Linq 2 SQL加入/組包含計數
var c = from C in db.Campaigns
join L in db.Links on C.id equals L.campaignID into CL
from CL2 in CL.DefaultIfEmpty()
join D in db.Divisions on CL2.divisionID equals D.id into CLD
from CLD2 in CLD.DefaultIfEmpty()
where C.ClientID == user.ClientID
group CLD2 by new { C.id, C.Name, Division = CLD2.Name, C.created } into G
select new {
CampaignName = G.Key.Name,
Campaignid = G.Key.id,
Division = G.Key.Division ?? "-",
Created = G.Key.created,
Links = G.Count(b => b.Name != null) };
我與它遇到的問題是,該司名稱爲空的每一行,當鏈接計數爲0(這不應該是)。
於是,我就寫了使用lambda不同的方式:
var c = from CLD in ( from C in db.Campaigns from L in db.Links.Where(w => w.campaignID == C.id).DefaultIfEmpty() from D in db.Divisions.Where(w => w.id == C.DivisionID).DefaultIfEmpty() where C.ClientID == user.ClientID select new { CampaignName = C.Name, Campaignid = C.id, Division = D.Name, Created = C.created } ) group CLD by new { id = CLD.Campaignid, Name = CLD.CampaignName, Division = CLD.Division, created = CLD.Created } into G select new { CampaignName = G.Key.Name, Campaignid = G.Key.id, Division = G.Key.Division ?? "-", Created = G.Key.created, Links = G.Count(b => b.Campaignid != null) };
在此查詢,該司的名稱正確顯示所有行,但是當鏈接的次數爲0,查詢將返回1代替。
我相信我在兩種情況下都很接近,但似乎無法找到正確的語法。歡迎任何建議。很高興爲任一查詢提供修復,但很想最終看到如何解決這兩個問題。
謝謝大家。