I’m looking for some advice on how best to get the first record when using a join with multiple tables, as demonstrated below.
I have three tables:
- Leads <– this should be unique in the results
- LeadAddresses (joining
table) - Addresses
Normally I’d join them like this:
from t2
in db.Leads
.Where(o => t1.LeadId == o.Lead_ID)
from t4
in db.LeadAddresses
.Where(o => t2.Lead_ID == o.Lead_ID)
.DefaultIfEmpty()
from t5
in db.Addresses
.Where(o => t4.Address_ID == o.Address_ID)
.DefaultIfEmpty()
(if this is bad practice, let me know 😉
I’m looking to get a property from the Addresses table (the one with, say, the maximum ID) for each Lead record and project to a model:
select new LeadGridModel
{
...
});
Example:
Lead Company | City | ZIP
==============================
Company 1 | Boston | 00000
Company 2 | Houston | 00001
This might look tricky, but you understand it part by part:
OrderByDescendingin combination withTake(1)we take the address with the maximum IDBe aware that this pattern forces a loop-join due to limitation of SQL Server. For small result sets this is usually not a problem.