In my post about rewriting Brad Abram’s MVC + Entity Framework example in VB, I pointed out a better way to query a collection of objects and return their entity references (eg, query products and bring along the category information) without writing a scary query filled with references, checks for nulls, etc.
But there was something bothering me about the query.
I went from this (Brad’s)
List<Product> products =TheProducts.Where(c => c.Category.CategoryName == category).ToList();//prepare the view by explicitly loading the categoriesproducts.FindAll(p => p.Category == null).ForEach(p => p.CategoryReference.Load());
var _prod = Northwind.Categories.
Where(c => c.CategoryName == id).
OrderBy(c => c.CategoryName).
Select(c => c.Products).
Which gives the same effect of ending up with a set of products and being able to drill into product.category.categoryname, etc.
But that query represents something that Entity Framework is not supposed to do, and I asked Danny Simmons about it.
Entity Framework will not perform actions that you did not request. I selected only products in my projection, yet I also got back categories. It was convenient, but it was against the promise of EF. I didn’t ask for categories.
In the end, a bug was filed, because indeed, that shouldn’t be happening.
However, it’s still VERY easy to explicitly tell EF to bring along a collection (eg if I query categories I can say “and give me those products while your at it) or an entity ref (query products and ask for the category) by using Include.
Here’s the same query for the MVC view even simpler.
var _products = Northwind.Products.Include(“Category”).
Where(p => p.Category.CategoryID == 1).ToList();
Sign up for my newsletter so you don't miss my conference & Pluralsight course announcements!