I did a little extension to ObjectQuery which goes like this
public static ObjectQuery<TEntity> Include<TEntity, TProperty>(this ObjectQuery<TEntity> query, Expression<Func<TEntity, TProperty>> expression) where TEntity : class
{
string name = expression.GetPropertyName();
return query.Include(name);
}
which also requires
public static class ExpressionExtensions
{
public static string GetPropertyName<TObject, TProperty>(this Expression<Func<TObject, TProperty>> expression) where TObject : class
{
if (expression.Body.NodeType == ExpressionType.Call)
{
MethodCallExpression methodCallExpression = (MethodCallExpression)expression.Body;
string name = ExpressionExtensions.GetPropertyName(methodCallExpression);
return name.Substring(expression.Parameters[0].Name.Length + 1);
}
return expression.Body.ToString().Substring(expression.Parameters[0].Name.Length + 1);
}
private static string GetPropertyName(MethodCallExpression expression)
{
MethodCallExpression methodCallExpression = expression.Object as MethodCallExpression;
if (methodCallExpression != null)
{
return GetPropertyName(methodCallExpression);
}
return expression.Object.ToString();
}
}
with that you can do
var context = new DataContext();
var employees = context.Employees.Include(e => e.Department);
which is going to be check at compile time. If i remember correctly, this methods doesn't work for many-to-many relationship but it works for stuff like
var item = context.Employees.Include(e => e.Department.Manager);
Good luck to you