动态Linq到OrderBy对象嵌套在IEnumerable中

时间:2015-01-09 16:26:08

标签: c# .net linq nhibernate dynamic-linq

我试图通过列表项的属性来编写一些动态linq,以便与NHibernate一起使用

public class Company
{
    public string Name { get; set; }
    public List<Employee> Employees { get; set; }
}

public class Employee
{
    public string Name{get; set;}
    public string PayrollNo{get; set;}

}

在这个例子中,它可以像PayrollNumber一样返回所有公司和订单。

使用标准linq,Repository方法看起来像这样。

var companies = session.Query<Company>()
    .OrderBy(x => x.Pieces.FirstOrDefault().PayrollNo)
    .FetchMany(x => x.Employees)

我想将此更改为动态linq以按列标题排序

 var companies = session.Query<Company>()
    .OrderByName("Employees.PayrollNo"), isDescending)
    .FetchMany(x => x.Employees)

我采用了与Dynamic LINQ OrderBy on IEnumerable<T>编写扩展方法

中的答案类似的方法

然后用递归钻取

    public static IQueryable<T> OrderByName<T>(this IQueryable<T> source, string propertyName, Boolean isDescending)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (propertyName == null) throw new ArgumentNullException("propertyName");

        var properties = propertyName.Split('.');
        var type = GetNestedProperty(properties, typeof(T));
        var arg = Expression.Parameter(type.GetProperty(properties.Last()).PropertyType, "x");
        var expr = Expression.Property(arg, properties.Last());

        Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
        LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);

        String methodName = isDescending ? "OrderByDescending" : "OrderBy";
        object result = typeof(Queryable).GetMethods().Single(
            method => method.Name == methodName
                    && method.IsGenericMethodDefinition
                    && method.GetGenericArguments().Length == 2
                    && method.GetParameters().Length == 2)
            .MakeGenericMethod(typeof(T), type)
            .Invoke(null, new object[] { source, lambda });
        return (IQueryable<T>)result;
    }


    //Walk the tree of properties looking for the most nested in the string provided
    static Type GetNestedProperty(string[] propertyChain, Type type) 
    {
        if (propertyChain.Count() == 0)
            return type;

        string first = propertyChain.First();
        propertyChain = propertyChain.Skip(1).ToArray(); //strip off first element

        //We hare at the end of the hierarchy
        if (propertyChain.Count() == 0)
            return GetNestedProperty(propertyChain, type);

        //Is Enumerable
        if (type.GetProperty(first).PropertyType.GetInterfaces().Any(t => t.Name == "IEnumerable"))
            return GetNestedProperty(
                propertyChain,
                type.GetProperty(first).PropertyType.GetGenericArguments()[0]);

        return GetNestedProperty(
            propertyChain,
            type.GetProperty(first).PropertyType.GetProperty(propertyChain.FirstOrDefault()).GetType());

    }

我在OrderByName扩展方法中生成表达式时遇到困难。我现在尝试了很多东西,但问题是公司类中不存在薪资号码。

我想要实现的目标是什么?

对此的任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

NHibernate还有其他更好的查询API。

string property = "Employees.PayrollNo";

var query = session.QueryOver<Company>()
    .Fetch(x => x.Employees).Eager;

// Join on the associations involved
var parts = property.Split('.');
var criteria = query.UnderlyingCriteria;
for (int i = 0; i < parts.Length - 1; i++)
{
    criteria.CreateAlias(parts[i], parts[i]);
}
// add the order
criteria.AddOrder(new Order(property, !isDescending));

var companies = query.List();