English 中文(简体)
Is an outer join possible with Linq to Entity Framework
原标题:

There are many examples of outer join using Linq to Sql, all of them hinging on DefaultIfEmpty() which is not supported with Linq to Entity Framework.

Does this mean that outer join is not possible with Linq to Entity using .NET 3.5 (I understand that DefaultIfEmpty is coming with 4.0 --- but that s not an option at this time for me)

Could somebody please provide a concise example using Linq to EntityFramework.

最佳回答

In LINQ to Entities, think in terms of relationships rather than SQL joins. Hence, the literal equivalent of a SQL outer join on an entity Person with a one to zero or one relationship to CustomerInfo would be:

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

L2E will coalesce the join, so that if CustomerInfo is null then the whole expression evaluates to null. Hence the cast to a nullable bool, because the inferred type of non-nullable bool couldn t hold that result.

For one-to-many, you generally want a hierarchy, rather 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 like a left join insofar as you still get orders with no details, but it s a graph like OO rather than a set like SQL.

问题回答

暂无回答




相关问题
IEnumerable to array of parameter

Using linq? and XML is there a way to convert this IEnumerable to a string array of the value parameter? List<string> idList = new List<string>(); foreach (XElement idElement in word....

linq query for tag system - search for multiple tags

I have two tables, Tags(tagid, postid, tagname) and posts(postid, name, ...) now i want to make a query that returns me all posts that have a generic amount of tags. like: i want all posts that have ...

Linq operations against a List of Hashtables?

I m working with a set of legacy DAO code that returns an IList, where each Hashtable represents the row of a dynamically executed SQL query. For example, the List might contain the following records/...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

How to filter duplicate list items

i have list of items IList with data that looks list this: GenId TestMode 1 0 1 1 3 0 3 1 4 NULL 2 NULL i want to remove the index ...

C# Grouping/Sorting a Generic List<> using LINQ

Im looking to group and sort a Generic List<>. I have a list of objects representing files and each of these objects has a FileName, FileType and FileDate property. FileType is defined as an ...

热门标签