Entity Framework Tip #1: Loading Grandchildren

When calling .FindById(), it's a relatively simple task, to have it include child properties explicitly. Simply add a lambda expression.

myRepository.FindById(1, x=>x.ChildList);

This will ensure that the ChildListis populated and not null.

But what if you need to ensure a GrandChildren entity is populated as well? Writing this won't work because ChildList is a collection.

myRepository.FindById(1, x=>x.ChildList.GrandChildren);

What you need to do, is use .Select()

myRepository.FindById(1, 
        x=>x.ChildList, 
        x.ChildList.Select(y=>y.GrandChildren)
        );

Simple...albeit non-intuitive.

Written on June 11, 2013