我正在尝试将复杂(而且相当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
表中是否存在任何值,查询都应返回所有Facilites
和ProjectedCashFlows
信息。
不幸的是,此查询没有这样做 - 当Customer
表中的工具存在时,它只返回Facilities
和ProjectedCashFlows
信息。
我使用MonthCalender
表列出了一年中的每个月。
相关的表格信息是:
客户
设施
ProjectedCashFlows
MonthsCalendar
作为一个例子,我有一个客户在Facilities
表中有4行,但是其中2个设施没有出现在ProjectedCashFlows
表中,因此它们没有显示。
如果ProjectedCashFlows
中不存在条目,则应采用ExpectedMonth& ExpectedYear来自CalendarMonths
表,为ExpectedAmount返回0并使用Facilities
表中的FacilityId。
你可能已经解决了我刚刚开始使用LINQ。
有人能指引我走向正确的方向吗?
答案 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
))