I am trying to convert a complex (and rather hacky) dynamic SQL query in to a LINQ query.
I have the following LINQ query so far:
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
}
);
I am trying to retrieve details from a Customer table that has a one-to-many relationship with a Facilities table. I am then trying to retrieve any details located in the ProjectedCashFlows
The problem I am having is that the query should return all Customer and Facilites information regardless of whether any values exist in the ProjectedCashFlows table.
Unfortunately this query is not doing that – it is only returning Customer and Facilities information when the Facility exists in the ProjectedCashFlows table.
I have used a MonthCalender table to list out each month in the year.
The relevant table information is:
Customers
- CustomerCode
- CustomerName
- PrimaryArmId
Facilities
- CustomerCode
- FacilityId
- FacilityCurrencyId
- FaciliyLimit
- FacilityDescription
ProjectedCashFlows
- CustomerCode
- FacilityId
- ExpectedYear
- ExpectedMonth
- ExpectedAmount
- ProjectedCashFlowStatusId
MonthsCalendar
- ExpectedMonth
- ExpectedYear
As an example I have a customer that has 4 rows in the Facilities table however, 2 of these facilities do not appear in the ProjectedCashFlows table so they are not being displayed.
If an entry doesn’t exist in ProjectedCashFlows it should take the ExpectedMonth & ExpectedYear from the CalendarMonths table, return 0 for the ExpectedAmount and use the FacilityId from the Facilities table.
As you can probably work out I have just started to use LINQ.
Can anyone poke me in the right direction?
Your query uses
passuming it is non-null:But you’ve used
DefaultIfEmpty()which will logically create a sequence with a single null value when there are no ProjectedCashFlows.So basically you need something like: