Is it feasible to do an outside join with Linq to Entity Framework?

entity-framework left-join linq

Question

There are several instances of outer joins in Linq to SQL, each of which depends onDefaultIfEmpty() which Linq to Entity Framework does not support.

Does this imply that Linq to Entity using.NET 3.5 cannot do an outer join? (I am aware that DefaultIfEmpty will be available with 4.0, but for me, it is not an option right now.)

Could someone, utilizing Linq to EntityFramework, provide a brief example.

1
18
11/20/2009 1:58:59 PM

Accepted Answer

Consider relationships while using LINQ to Entities rather than SQL joins. Consequently, an entity's literal equivalent of a SQL outer joinPerson having a connection of one to zero or oneCustomerInfo such as:

var q = from p in Context.People
        select new
        {
            Name = p.Name,
            IsPreferredCustomer = (bool?)p.CustomerInfo.IsPreferredCustomer
        };

If CustomerInfo is null, L2E will coalesce the join such that the whole expression evaluates to null. Because the inferred type of non-nullable bool couldn't contain that result, the cast was made to a nullable bool.

In general, a hierarchy is preferred for one-to-many queries than a flat, SQL-style result set:

var q = from o in Context.Orders
        select new 
        {
            OrderNo = o.OrderNo,
            PartNumbers = from od in o.OrderDetails
                          select od.PartNumber
        }

This is similar to a left join in that you still obtain orders without any information, but it uses a graph similar to OO instead of a set similar to SQL.

36
11/20/2009 2:45:59 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow