通用方法因选择器而失败

时间:2014-05-27 16:24:28

标签: asp.net-mvc entity-framework generics

orderselector:

Func<Model.Candidate, object> orderselector = p => p.UpdateDate;

SelectListbyDesc方法调用:

helper.Result= Model.GeneralDataAccessor.SelectListbyDesc<Model.Candidate,
OrgCandidateSearch.Result, object>(predicate, selector, orderselector, 
(model.PageNo - 1) * model.Count, model.Count);

我希望helper.Result根据UpdateDate按降序排列结果。 但结果是按升序排列。 SelectListbyDesc可以正常使用其他任何内容。

我可以先写一下(p=>p.UpdateDate).OrderByDescending()吗?

SelectListbyDesc:

 public static List<T2> SelectListbyDesc<T1, T2, T3>(Expression<Func<T1, bool>> predicate, Func<T1, T2> selector, Func<T1, T3> keySelector,
        int skip = 0, int take = 0, bool addRelationalProperties = true)
        where T1 : class
    {
        string typeName = GetTypeName<T1>();
        using (ObjectContext context = GetContext())
        {
            ObjectSet<T1> objectSet = context.CreateObjectSet<T1>();
            if (addRelationalProperties)
            {
                if (take == 0)
                    return Include(objectSet, GetIncludeProperties<T1>()).Where<T1>(predicate).OrderBy<T1, T3>(keySelector).Select<T1, T2>(selector).ToList<T2>();
                else
                    return Include(objectSet, GetIncludeProperties<T1>()).Where<T1>(predicate).OrderBy<T1, T3>(keySelector).Skip(skip).Take(take)
                        .Select<T1, T2>(selector).ToList<T2>();
            }
            else
            {
                if (take == 0)
                    return objectSet.Where<T1>(predicate).OrderByDescending<T1, T3>(keySelector).Select<T1, T2>(selector).ToList<T2>();
                else
                    return objectSet.Where<T1>(predicate).OrderByDescending<T1, T3>(keySelector).Take(take).Select<T1, T2>(selector).ToList<T2>();
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

好吧,如果没有办法改变项目的排序方式,有一种方法可以将排序值改为排序。

Func<Model.Candidate, object> orderselector = p => DateTime.MaxValue - (p.UpdateDate - DateTime.MinValue);

逻辑是这样的:p.UpdateDate - DateTime.MinValue给出了p.UpdateDate的时间跨度,并从DateTime.MaxValue中减去它给了我们与我们最初相反的DateTime实例。< / p>

但请注意,这看起来更像是黑客而不是真正的解决方案。真正的解决方案当然是在SelectListbyDesc`中实现适当的条件排序。