Entity Framework Include with Func
In Northwind DB, if you want to load categories with products, you will use Include method:
context.Categories.Include("Products")
But what I really find bad is the fact that Products is a string. When we use LINQ, we can't understand it.
So I define an extension method:
public static class ObjectQueryExtension
{
public static ObjectQuery<T> Include<T>(this ObjectQuery<T> mainQuery, Expression<Func<T, object>> subSelector)
{
return mainQuery.Include(((subSelector.Body as MemberExpression).Member as Reflection.PropertyInfo).Name);
}
}
and I can now doing this:
context.Categories.Include(c => c.Products)
which is I think really better. Isn't it?