Linq-To-Sql中的左外连接问题

时间:2011-04-14 03:26:01

标签: c# sql database linq-to-sql

嗨我有5张桌子。必要的关系如下

期间 ID 开始日期 结束日期 请将isDeleted

代码 ID 名称

YearlyTarget ID 代码ID PeriodId YTAmount 请将isDeleted

AlteredTarget ID YearlyTargetId AltAmount 请将isDeleted

实际 ID AlteredTargetId ActualAmount 请将isDeleted

我有4个季度的年度数据。所有季度都存在YearlyTarget,Q1为AlteredTarget,none为None。

我的查询如下:

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 个答案:

答案 0 :(得分: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

和另一个相同。请注意,如果存在实际值 do ,则会更改查询的含义,但它们都已删除。我怀疑它会改变它你想要的行为,但是......