in .NET Framework

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:

1
2
3
4
using (CommuicationsEntities entities = new CommuicationsEntities())
{
entities.Order.Include("OrderDetails");
}

To a nice strongly typed includes using a IncludeBuilder class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class IncludeBuilder
{
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.

1
2
3
4
IncludeBuilder _include = new IncludeBuilder();
_include.Add(a => a.Orders);
ObjectQuery customers= DataContext.Servers;
return _include.Includes(customers).Execute(MergeOption.NoTracking).ToList();

References:

http://davidkiff.co.uk/post/2009/08/27/EF-Strongly-Typed-ObjectQuery3cT3eInclude%28e2809ce2809d%293b.aspx