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
我遇到的问题是,查询应该返回所有Customer
和Facilites
信息,无论ProjectedCashFlows
表中是否存在任何值。
不幸的是,这个查询没有这样做-它只返回Customer
和Facilities
信息,当设施存在于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。
有谁能给我指个方向吗?您的查询使用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
))