Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I most elegantly express left join with aggregate SQL as LINQ query

Tags:

SQL:

SELECT    u.id,    u.name,    isnull(MAX(h.dateCol), '1900-01-01') dateColWithDefault FROM universe u LEFT JOIN history h     ON u.id=h.id     AND h.dateCol<GETDATE()-1 GROUP BY u.Id, u.name 
like image 817
vzczc Avatar asked Aug 03 '08 21:08

vzczc


People also ask

Can we use left join in LINQ?

You can use LINQ to perform a left outer join by calling the DefaultIfEmpty method on the results of a group join.

Can I join a table to a list using LINQ?

You probably found out that you can't join an Entity Framework LINQ query with a local list of entity objects, because it can't be translated into SQL. I would preselect the database data on the account numbers only and then join in memory.

How does a LINQ query transform to a SQL query?

LINQ to SQL translates the queries you write into equivalent SQL queries and sends them to the server for processing. More specifically, your application uses the LINQ to SQL API to request query execution. The LINQ to SQL provider then transforms the query into SQL text and delegates execution to the ADO provider.


1 Answers

A solution, albeit one that defers handling of the null value to the code, could be:

DateTime yesterday = DateTime.Now.Date.AddDays(-1);

var collection=     from u in db.Universe     select new     {         u.id,         u.name,         MaxDate =(DateTime?)        (            from h in db.History            where u.Id == h.Id            && h.dateCol < yesterday            select h.dateCol         ).Max()     }; 

This does not produce exactly the same SQL, but does provide the same logical result. Translating "complex" SQL queries to LINQ is not always straightforward.

like image 96
vzczc Avatar answered Sep 19 '22 09:09

vzczc