LINQ的查询扩展

时间:2010-02-05 15:09:29

标签: c# linq-to-entities

我有一些代码用于在linq中强类型Includes(),就像这样......

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);
    }

我的问题是,无论如何我可以为任何级别的连续包括编写更通用的功能帐户吗?而不是必须重写它说3,4等,包括类型?

1 个答案:

答案 0 :(得分:2)

我想通过连续包含你的意思是额外的子选择器。

如果是这样,那么下面的函数使用一个参数数组用于附加的子选择器(在第一个之后),同时保持第一个表达式与其他子表达式相同的类型T.

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());
}