EF Strongly Typed ObjectQuery.Include
The problem that I faced was having to put up with “hard coded” strings in the ObjectQuery.Include function to load related objects through POCO objects in the Entity Framework. This faced challenges when I renamed columns in the Model which caused a run-time error when recompiling and re-starting the application. Thanks to David Kiff, we can now change the code from being strings:
{
entities.Order.Include("OrderDetails");
}
To a nice strongly typed includes using a IncludeBuilder class.
{
private readonly List _propertiesToInclude;
public IncludeBuilder()
{
_propertiesToInclude = new List();
}
public void Add(Expression<Func<T, object>> propertySelector)
{
MemberExpression memberExpression = propertySelector.Body as MemberExpression;
if (memberExpression == null)
throw new ArgumentException("Parameter propertySelector must be a MemberExpression");
_propertiesToInclude.Add(memberExpression.Member.Name);
}
public ObjectQuery Includes(ObjectQuery query)
{
foreach (string include in _propertiesToInclude)
{
query = query.Include(include);
}
return query;
}
}
the following code calls the include builder, includes the relationship and gets a simple list with no tracking on the POCO objects.
_include.Add(a => a.Orders);
ObjectQuery customers= DataContext.Servers;
return _include.Includes(customers).Execute(MergeOption.NoTracking).ToList();
References:


