I am trying to create a LINQ to SQL query and am really stumped.
I have a database with multiple tables and can create a query that successfully returns the result from a single join. The problem I am having is introducing the second join.
The SQL statement was easy enough to generate
USE InlandMarina
SELECT *
FROM Slip s LEFT JOIN Lease l ON s.id = l.slipid
WHERE GETDATE() > l.EndDate OR ISNULL(l.startdate, '') = ''
I've generated two functional LINQ queries that individually return the desired results, but can't marry the two successfully.
var nulledSlips = from slips in theContext.Slips
join nulled in theContext.Leases on slips.ID equals nulled.SlipID into slipsNulled
from nulledEndDate in slipsNulled.Where(nulled => nulled.EndDate==null).DefaultIfEmpty()
Returns all slips that have no end date set in the database (null), they've never been leased.
from expiredSlips in theContext.Slips
join leased in theContext.Leases on slips.ID equals leased.SlipID into allSlips
from leased in allSlips
where leased.EndDate < DateTime.Today
Returns slips that the lease has expired on.
What I'd like to be able to do is combine the two queries somehow into one that returns all slips that have either never been leased out or have had their leases expire.
Any help would be greatly appreciated, I've been at this for two days and can't see the forest for the trees anymore.
Schema is four tables; Lease, Slip, Dock, Location. Lease PK ID FK SlipID
Slip PK ID FK DockID
Dock PK ID FK LocationID
Location PK ID
Revised query is:
var expiredSlips = from slips in theContext.Slips
join nulled in theContext.Leases on slips.ID equals nulled.SlipID into slipsNulled
from nulledEndDate in slipsNulled.Where(nulled => nulled.EndDate == null).DefaultIfEmpty()
join leased in theContext.Leases on slips.ID equals leased.SlipID into allSlips
from leased in allSlips.Where(leased=> leased.EndDate < DateTime.Today).DefaultIfEmpty()
Returns:
<SlipsDTO>
<SlipID>1000</SlipID>
<Width>8</Width>
<Length>16</Length>
<DockID>1</DockID>
<WaterService>true</WaterService>
<ElectricalService>true</ElectricalService>
<MarinaLocation>Inland Lake</MarinaLocation>
<LeaseStartDate xsi:nil="true" />
<LeaseEndDate xsi:nil="true" />
</SlipsDTO>
Yielding everything. If I remove the last .DefaultIfEmpty() I get a result set of only the slips that have had a lease; current or expired.