views:

30

answers:

1

I want to load an entity and it's children conditionally (I only want to eager load the children when the child.IsActive == true). How do I perform the following?

var parent = 
    from p in db.tblParents.Include("tblChildren") <-- where tblChildren.IsActive == true
    where p.PrimaryKey == 1
    select p;

NOTE: I do not want to return an anonymous type.

Thanks.

+1  A: 
Morteza Manavi
I neglected to mention that I do not want to return an anonymous type... I need to return an object (or collection) of type tblParent.
alex.davis.dev
Sure, I added another code snippet that gives you a strong typed Parent object which contains all the children who matched the criteria. Please have a look.
Morteza Manavi
This makes sense... however, we have moved out of the realm of eager loading.
alex.davis.dev
So I am still back at my original question... in the interim, I have just used Linq to filter out records in memory...
alex.davis.dev
I am afraid there is no way to have a "Conditional Eager Loading" with include. The API for Include() method just has not been designed that way. The work around is to leverage **"Filtered Projection"** or get it done by implement **"Two Tracked Queries"**, my code snippets covers these two methods respectively. It would have been nice if we could code something like this though: Include("tblChildren", c => c.IsActive == true).
Morteza Manavi
Fair enough. I had a feeling this was the case. Thanks.
alex.davis.dev