EF Query to Get Union of All Child Collections

790 Views Asked by At

Assuming I have an Entity Framework 4.2 class like this:

class Company
{
    public int ID { get; set; }
    public ICollection<Employee> Employees { get; set; }
}

And I have collection like this:

public ICollection<Company> Companies { get; set; }

What's an efficient way to build a list of all employees in the entire Companies collection? I do not need to worry about duplicates.

Note: I'm trying to do it without an Entity Framework context--just using the Companies collection. However, if this entails a huge performance hit, I could get a context if necessary.

1

There are 1 best solutions below

3
On BEST ANSWER

I'm not sure what you're trying to achieve, but to query the data you'll want to use the DbContext.

You can configure you context to automatically load the related entities by setting LazyLoadingEnabled to true, or explicitly, i.e. when querying the data, include the path to the employees, using the Include extension provided with EF > 4.0.

As soon as all companies are there you could linq it using the SelectMany method. I haven't checked, but AFAIK, LINQ to SQL will execute the query as one bunch on demand.

If you insist not to expose your DbContext or if you use a different underlying context, I would suggest you to wrap it up in a repository that does the SelectMany behind the since, but your friend are Include and SelectMany.