资源库使用排序依据 [英] Repository With OrderBy
问题描述
我试图使该有权责令基于一个之类的参数结果的方法库类。我需要把它作为参数传递,因为我想是非常严谨的,我的资料库不返回IQueryable的,只有返回列表。问题是,我不知道如何使它使其符合下列要求:
I'm trying to make a repository class that has a method to order the results based upon a "sort" parameter. I need to pass it as a parameter since I'm trying to be very strict that my repository doesn't return IQueryable and only returns List. The problem is that I have no idea how to make it so that it meets the following requirements:
- 允许多个列。
- 强类型到的返回(无字符串列作为参数)的实体。
- 能够设置一个特定的列递减。
这甚至可能还是没用,一个库允许与订货回来?如果存储库只是能够执行CRUD操作?也许返回IQueryable的将是最好的选择吗?
Is this even possible or is it useless that a Repository allows returning with ordering? Should the repository be just able to perform CRUD operations? Maybe returning IQueryable would be the best option?
推荐答案
也许你需要的东西是这样的:
Perhaps you need something like this:
public class Ordering<T>
{
private readonly Func<IQueryable<T>, IOrderedQueryable<T>> transform;
private Ordering(Func<IQueryable<T>, IOrderedQueryable<T>> transform)
{
this.transform = transform;
}
public static Ordering<T> Create<TKey>
(Expression<Func<T, TKey>> primary)
{
return new Ordering<T>(query => query.OrderBy(primary));
}
public Ordering<T> ThenBy<TKey>(Expression<Func<T, TKey>> secondary)
{
return new Ordering<T>(query => transform(query).ThenBy(secondary));
}
// And more for the descending methods...
internal IOrderedQueryable<T> Apply(IQueryable<T> query)
{
return transform(query);
}
}
然后,客户机可以创建一个订购&LT; T&GT;
要传递到存储库,而repositry可以调用应用
与的IQueryable&LT; T&GT;
。这是否有意义?
Then a client can create an Ordering<T>
to be passed into the repository, and the repositry can call Apply
with the IQueryable<T>
. Does that make sense?
样品(略带傻气)使用方法:
Sample (slightly silly) use:
var ordering = Ordering<FileInfo>.Create(fi => fi.Length)
.ThenBy(fi => fi.Name);
这篇关于资源库使用排序依据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!