Search code examples
entity-frameworkentity-framework-4

Conditional eager loading?


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.


Solution

  • One way for doing so is:

    var parent = from p in db.tblParents where p.PrimaryKey == 1
                 select new {
                     Parent = p,
                     Children = p.tblChildren.Where(c => c.IsActive == true)
                 }.ToList();
    


    However, you might not like the idea to return an anonymous type, then I would suggest to code it this way:

    var parent = (from p in db.tblParents where p.PrimaryKey == 1).Single();
    var childrens = ctx.Contacts.Where(c => c.ParentID == 1 && c.IsActive == true);
    foreach (var child in childrens) {
       parent.tblChildren.Add(child);
    }