2011-04-14 76 views
0

嗨,我有5個表格。必要的關係如下所示在Linq-To-SQL中左外部連接問題

標識 起始日期 結束日期 請將isDeleted

代碼 標識 名稱

YearlyTarget 標識 代碼ID PeriodId YTAmount請將isDeleted

AlteredTarget 標識 YearlyTargetId AltAmount 請將isDeleted

實際 標識 AlteredTargetId ActualAmount 請將isDeleted

我有一年的數據4個季度。 YearlyTarget存在於所有季度,第一季度爲AlteredTarget,第一季度爲實際。

我的查詢如下:

from cl in this.Context.Codes  
join ytl in this.Context.YearlyTargets on cl.Id equals ytl.CodeId  
join pl in this.Context.Periods on ytl.PeriodId equals pl.Id  
join atl in this.Context.AlteredTargets on ytl.Id equals cdpl.YearlyTargetId into ccl  
join al in this.Context.Actuals on ytl.Id equals al.AlteredTargets.YearlyTargetId into cal 
from cc in ccl.DefaultIfEmpty()  
from ca in cal.DefaultIfEmpty() 
where cc.IsDeleted == false && ca.IsDeleted == false 
select new  
{  
    Year = pl.EndDate.Year,  
    PeriodType = (PeriodType)pl.PeriodType,  
    PeriodName = pl.StartDate,  
    CodeName = cl.CodeName,  
    YT = ytl.TargetAmount,  
    CDP = cc.AltAmount,  
    Actual = ca.ActualAmount  
}; 

查詢將返回空。有人可以告訴我這個查詢有什麼問題嗎?謝謝!!!

回答

1

我的猜測是這是where條款,這是搞砸了你。不要忘記,ccca可以爲空。嘗試改變where子句:

where (cc == null || !cc.IsDeleted) && (ca == null || !ca.IsDeleted) 

您也可能會需要改變,你用ccca的預測:

CDP = cc == null ? 0 : cc.AltAmount,  
Actual = ca == null ? 0 : ca.ActualAmount 

我現有where條款可能更好的替代方法是把在檢查IsDeleted進入加入:

join al in this.Context.Actuals.Where(x => !x.IsDeleted) 
    on ytl.Id equals al.AlteredTargets.YearlyTargetId into cal 

與同爲 另一個。請注意,如果實際值存在但它們全部被刪除,這將更改查詢的含義。我懷疑它改變了你想要的行爲雖然...

+0

非常感謝,在連接條款中添加驗證解決了我的問題。 – Purusartha 2011-04-14 06:46:14