Search code examples
entity-frameworksilverlight-4.0wcf-ria-services

Linq Query of active child entities


I didn't know what to write in the title of the question. Here's my sample. I have a Foo class which has a collection of Bars as follows:

public class Foo  
{  
    public bool Active {get; set;}  
    public ICollection<Bar> Bars {get; set;}  
}  

public class Bar
{
    public bool Active {get; set;}
}

As you can see both Foos and Bars can be set as inactive (Active = false). I nee to write a service (RIA) which will return every active Foo with its actives Bars.
So this is what I have so far:

public IQueryable<Foo> GetFoos()
{
    return ObjectContext.Foos.Where(f => f.Active)
                             .Include("Bars");
}

The thing is that the above query returns every active Foo with every single Bar, so how do I include only active Bars ?


Solution

  • The Include method is part of LazyLoading. Lazy loading is either all or nothing, thus you can not tell the EF to only load some Bars.

    What you can try to do, however, is using an anonymous object as a result:

    context.Foos
    .Where(f => f.Active)
    .Select(f => new { Foo = f, Bars = f.Bars.Where(b => b.IsActive });