zzMzz
zzMzz

Reputation: 467

Linq Query With Multiple Left Joins

I'm very novice with Linq but I have to convert several complicated SQL queries into Linq so I bought a copy of Linqer. Unfortunately I know have a SQL query Linqer can't convert to Linq because Linqer cannot convert SQL with sub joins. I am hoping someone can help me with the Linq code for this SQL query:

SELECT v.*, rci.CustomId, ci.EntryTime As CheckInTime, ci.Operator As CheckInOperator, 
    cis.Name As CheckInStation, co.EntryTime As CheckOutTime, co.Operator As CheckOutOperator, 
    cos.Name As CheckOutStation, cat.Name As Category, clr.Name As Clearance, r.ReasonForVisit As Reason, 
    s.SiteId + ' -- ' + s.SiteName As Site, e.LastName + ', ' + e.FirstName As Employee 
    FROM ((((((((((Visitor v LEFT JOIN VisitorEntry ci ON v.CheckInId = ci.Id) 
    LEFT JOIN VisitorEntry co ON v.CheckOutId = co.Id) 
    LEFT JOIN Station cis ON ci.StationId = cis.Id) 
    LEFT JOIN Station cos ON co.StationId = cos.Id) 
    LEFT JOIN Category cat ON v.CategoryId = cat.Id) 
    LEFT JOIN Clearance clr ON v.ClearanceId = clr.Id) 
    LEFT JOIN Reason r ON v.ReasonId = r.Id) 
    LEFT JOIN Site s ON v.SiteId = s.Id) 
    LEFT JOIN Employee e ON v.EmployeeId = e.Id) 
    LEFT JOIN RecordCustomId rci ON v.Id = rci.ParentId) 
    WHERE 1=1 

(I have several SQL queries similar to this one that I need to convert into Linq so that is why I have the "WHERE" placeholder in the query.)

Also I've been looking at this blog post but I'm still having trouble understanding how to translate my query: http://codingsense.wordpress.com/2009/06/16/multiple-list-left-join-in-linq/

Thanks! Mike

Upvotes: 0

Views: 948

Answers (1)

Coding Flow
Coding Flow

Reputation: 21881

What is the point of all those brackets in your SQL, they don't seem to be doing anything, do you not get the exact same result if they are removed? You use the DefaultIfEmpty method to do left joins in linq. I presume you are using LinqToSql? Below in an example from a recent project i have worked on

return from app in pi_GetApplications()
       from names in app.tContact.tNames // Inner Join
       from addr in app.tContact.tAddresses.DefaultIfEmpty() // Left Outer Join
       select app;

This assumes you have the associations for the foreign keys defined in your DBML file so that LinqtoSql knows how the entities are related.

Upvotes: 2

Related Questions