LINQ丢弃结果

时间:2011-10-20 10:36:57

标签: c# linq linq-to-sql .net-3.5

我正在尝试将复杂(而且相当hacky)的动态SQL查询转换为LINQ查询。

到目前为止,我有以下LINQ查询:

var results = (
    from c in Customers
    from d in MonthCalendar
        join f in Facilities on c.CustomerCode equals f.CustomerCode
        join p in ProjectedCashFlows on f.FacilityId equals p.FacilityId into pj
                from p in pj.DefaultIfEmpty()                      
        where d.ExpectedYear == currentYear 
                && f.FacilityStatusId == 1
                && (p.ExpectedYear == null || d.ExpectedYear == p.ExpectedYear)
                && (p.ExpectedMonth == null || d.ExpectedMonth == p.ExpectedMonth)
                && c.PrimaryArmId == userId 
                && (p.ProjectedCashFlowStatusId == null || p.ProjectedCashFlowStatusId != 4)
        select new 
            {
                CustomerCode = c.CustomerCode,
                CustomerName = c.CustomerName,
                FacilityId = f.FacilityId,
                FacilityDescription = f.FacilityProductDescription,
                FacilityCurrency = f.FacilityCurrencyId,
                FacilityLimit = f.Limit,
                ExpectedYear = d.ExpectedYear,
                ExpectedMonth = d.ExpectedMonth,
                ExpectedAmount = p == null ? 0 : (double)p.ExpectedAmount

            }
            );

我正在尝试从Customer表中检索与Facilities表具有一对多关系的详细信息。然后我尝试检索位于ProjectedCashFlows

中的所有详细信息

我遇到的问题是,无论Customer表中是否存在任何值,查询都应返回所有FacilitesProjectedCashFlows信息。

不幸的是,此查询没有这样做 - 当Customer表中的工具存在时,它只返回FacilitiesProjectedCashFlows信息。

我使用MonthCalender表列出了一年中的每个月。

相关的表格信息是:

客户

  • CustomerCode
  • 客户名称
  • PrimaryArmId

设施

  • CustomerCode
  • FacilityId
  • FacilityCurrencyId
  • FaciliyLimit
  • FacilityDescription

ProjectedCashFlows

  • CustomerCode
  • FacilityId
  • ExpectedYear
  • ExpectedMonth
  • ExpectedAmount
  • ProjectedCashFlowStatusId

MonthsCalendar

  • ExpectedMonth
  • ExpectedYear

作为一个例子,我有一个客户在Facilities表中有4行,但是其中2个设施没有出现在ProjectedCashFlows表中,因此它们没有显示。

如果ProjectedCashFlows中不存在条目,则应采用ExpectedMonth& ExpectedYear来自CalendarMonths表,为ExpectedAmount返回0并使用Facilities表中的FacilityId。

你可能已经解决了我刚刚开始使用LINQ。

有人能指引我走向正确的方向吗?

1 个答案:

答案 0 :(得分:2)

您的查询使用p ,假设它为非空

where d.ExpectedYear == currentYear 
      && f.FacilityStatusId == 1
      && (p.ExpectedYear == null || d.ExpectedYear == p.ExpectedYear)
      // etc

但是你已经使用了DefaultIfEmpty(),当没有ProjectedCashFlows时,它将在逻辑上创建一个具有单个空值的序列。

所以基本上你需要这样的东西:

where d.ExpectedYear == currentYear 
      && f.FacilityStatusId == 1
      && (p == null ||
          ((p.ExpectedYear == null || d.ExpectedYear == p.ExpectedYear)
          // etc
          ))