Query Extension for LINQ

I have code for strongly typing. Includes () in linq, for example ...

public static ObjectQuery<T> Include<T>(this ObjectQuery<T> mainQuery, Expression<Func<T, object>> subSelector)
    {
        return mainQuery.Include(((subSelector.Body as MemberExpression).Member as System.Reflection.PropertyInfo).Name);
    }

    /// <summary>
    /// Old way: (from dbUser in DataSource.DataContext.Users.Include("UserSubscriptions.ChurchSubscriptions") select dbUser);
    /// New way: (from dbUser in DataSource.DataContext.Users.Include<Users, UserSubscriptions>(u => u.UserSubscriptions, s => s.ChurchSubscriptions) select dbUser);
    /// </summary>
    public static ObjectQuery<T> Include<T, Q>(this ObjectQuery<T> mainQuery, Expression<Func<T, object>> tSubSelector, Expression<Func<Q, object>> qSubSelector)
    {
        string tProperty = ((tSubSelector.Body as MemberExpression).Member as System.Reflection.PropertyInfo).Name;
        string qProperty = ((qSubSelector.Body as MemberExpression).Member as System.Reflection.PropertyInfo).Name;
        string path = string.Format("{0}.{1}", tProperty, qProperty);
        return mainQuery.Include(path);
    }

My question is, is there anyway I can write a more general function account for any level of sequential inclusion? Instead of rewriting it, say, 3, 4, etc. Include types?

+5
source share
1 answer

I suppose that by means of successive inclusions you mean additional subselements.

If so, then the following function uses an array of parameters for additional sub-selectors (after the first), while maintaining that the first expression is bound to the same type T as the others.

public static ObjectQuery<T> Include<T>(this ObjectQuery<T> mainQuery, Expression<Func<T, object>> tSubSelector, params Expression<Func<object, object>>[] subSelectors)
{
    var pathBuilder = new StringBuilder(((PropertyInfo)((MemberExpression)tSubSelector.Body).Member).Name);
    foreach (var selector in subSelectors)
    {
        pathBuilder.Append('.');
        pathBuilder.Append(((PropertyInfo)((MemberExpression)selector.Body).Member).Name);
    }

    return mainQuery.Include(pathBuilder.ToString());
}
+2
source

All Articles