LINQ下降结果

本文关键字:结果 LINQ | 更新日期: 2023-09-27 18:11:54

我正在尝试将一个复杂的(而且相当粗糙的)动态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
            }
            );

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

中的任何细节。

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

不幸的是,这个查询没有这样做-它只返回CustomerFacilities信息,当设施存在于ProjectedCashFlows表中。

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

相关表信息为:

  • CustomerCode
  • CustomerName
  • PrimaryArmId

  • CustomerCode
  • FacilityId
  • FacilityCurrencyId
  • FaciliyLimit
  • FacilityDescription

ProjectedCashFlows

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

MonthsCalendar

  • ExpectedMonth
  • ExpectedYear

作为一个例子,我有一个客户在Facilities表中有4行,然而,这些设施中的2个没有出现在ProjectedCashFlows表中,所以它们没有被显示。

如果一个条目在ProjectedCashFlows中不存在,它应该取ExpectedMonth &CalendarMonths表中的ExpectedYear, ExpectedAmount返回0,使用Facilities表中的FacilityId。

你可能知道我刚刚开始使用LINQ。

有谁能给我指个方向吗?

LINQ下降结果

您的查询使用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
          ))