Overmachine
Overmachine

Reputation: 1733

Convert this sql query to LINQ to Lambda Left Outer Join

I have trying to convert this sql query to Linq to lambda and i have no success i only have the records that are in the table places that match the id on the table requireddocuments i want the nulls too. The sql query works fine but the lambda doesn't

SQL Query.

  SELECT Document, Place, Record
   FROM RequiredApplicationDocuments LEFT OUTER JOIN Places ON
     RequiredApplicationDocuments.Id = Places.RequiredApplicationDocumentId
       WHERE Places.SecondPlaceId = 4 OR Places.SecondPlaceId IS NULL

Lambda

Database.RequiredApplicationDocuments.Join(Database.Placess, 
            ra => ra.Id, fa => fa.RequiredApplicationDocumentId, (fa, ra) =>
            new {Places = fa, RequiredApplicationDocument = ra}).DefaultIfEmpty().toList().Select(fa => new Places
                           {
                  FileName = fa.RequiredApplicationDocument.FileName,
                  LoanApplicationId = fa.RequiredApplicationDocument.LoanApplicationId,
                  Name = fa.RequiredApplicationDocument.Name,
                  RequiredApplicationDocument = fa.RequiredApplicationDocument.RequiredApplicationDocument,
                  Id = fa.Places.Id,
                  CreationDate = fa.RequiredApplicationDocument.CreationDate,
                  Contents = fa.RequiredApplicationDocument.Contents,
                  RequiredApplicationDocumentId = fa.RequiredApplicationDocument.RequiredApplicationDocumentId,
                  LoanApplication = fa.RequiredApplicationDocument.LoanApplication,
                  Type = fa.RequiredApplicationDocument.Type 
            }).AsQueryable();

Upvotes: 0

Views: 2718

Answers (1)

Ken Goodridge
Ken Goodridge

Reputation: 4011

use GroupJoin

This is more targeted to you SQL than to your LINQ

        var res = RequiredApplicationDocuments.GroupJoin(Places,
            p => p.Id,
            d => d.RequiredApplicationDocumentId,
            (d, places) => new
            {
                Document = d,

                Place = places.Where(p => p.SecondPlaceId == 4).FirstOrDefault(),

                // if don't want to exclude documents with "non-4" places only, 
                // remove this and last where clause
                // but this is what your SQL does
                HasNoPlaces = places.Count() == 0 

            }).Where(r => r.HasNoPlaces || r.Place != null);

Upvotes: 4

Related Questions