LINQ: How to Write INNER JOIN and WHERE Condition

146 Views Asked by At

I have two database tables--

ReconFinalCost (Id, LeaseDocNumber, SnapshotId)  
ReconSnapshot (Id, FiscalYear, FiscalQuarter)

ReconFinalCost.SnapshotId is a foreign-key to ReconSnapshot.Id.

In my C# code, I have a List<ReconFinalCost> leaselist. I want to write a LINQ command that inner joins the ReconFinalCost and ReconSnapshot tables on (ReconFinalCost.SnapshotId == ReconSnapshot.Id) and KEEPS all ReconFinalCost items in List<ReconFinalCost> leaselist for which there DOES NOT EXIST another ReconFinalCost item with an identical LeaseDocNumber but for which there is a SnapshotId associated with a ReconSnapshot with identical FiscalYear, but larger FiscalQuarter.

Here's that query, which I'm trying to write in LINQ, in SQL. I want to KEEP all items in List<ReconFinalCost> leaselist that are returned by the SQL query.

select * from "ReconFinalCost"
inner join "ReconSnapshot" on "ReconFinalCost"."SnapshotId" = "ReconSnapshot"."Id"
where NOT EXISTS (
    SELECT 1 FROM "ReconFinalCost" B
    inner join "ReconSnapshot" RS2 on RS2."Id" = B."SnapshotId"
    where  "ReconFinalCost"."LeaseDocNumber" = B."LeaseDocNumber" and             
           ( RS2."FiscalYear" = "ReconSnapshot"."FiscalYear" and 
             RS2."FiscalQuarter" > "ReconSnapshot"."FiscalQuarter" )
    )

So far I have:

List<ReconFinalCost> leaselist;
List<ReconFinalCost> originalLeaseList = leaselist;
leaselist = leaselist
    .Where(x => !originalLeaseList.Any(
        y => y.LeaseDocNumber == x.LeaseDocNumber &&
            getIdsOfFutureQuarterSnapshots(x.SnapshotId).Any(
                 futureSnapshotId => futureSnapshotId == y.SnapshotId) ) )
    .OrderBy(x => x.LeaseDocNumber).ToList();
...

private List<long> getIdsOfFutureQuarterSnapshots(long? snapshotId)
{
     // this function returns a list of Ids of ReconSnapshots with the same (FiscalYear) as that of snapshotId, except in a FUTURE quarter
     ReconSnapshot givenSnapshot = repository.GetReconSnapshotByID( (int)snapshotId );
     return _context.ReconSnapshots.Where(r =>   r.FiscalYear == givenSnapshot.FiscalYear && 
            r.FiscalQuarter > givenSnapshot.FiscalQuarter ).Select(r => r.Id).ToList();
}

What is the LINQ syntax for inner joining the ReconFinalCost and ReconSnapshot tables on (ReconFinalCost.SnapshotId == ReconSnapshot.Id), and then specifying the where clause for identical FiscalYear but larger FiscalQuarter, instead of having to call a separate function like I've done above?

0

There are 0 best solutions below