我正在使用<代码>Entity Framework 4.1和 交存式
。
I am trying to create methods that will be used throughout most scenarios. I am trying to create a method that brings back records and sorts it according to the order criteria supplied. It can be sorted by 1, 2 or 3 columns. I want this to be specified. I found the following code in the Orchard framework
.
在<代码>上 托存接口代码>有以下(我没有其他方法):
public interface IRepository<T>
{
IEnumerable<T> Fetch(Expression<Func<T, bool>> predicate);
IEnumerable<T> Fetch(Expression<Func<T, bool>> predicate, Action<Orderable<T>> order);
}
实施如下:< 编码> 可计算和提炼;T> Fetch (Expression<Func<T, bool>>coment, Action<Orderable<T>> order);:
public class Repository<T> : IRepository<T>
{
public virtual IQueryable<T> Fetch(Expression<Func<T, bool>> predicate)
{
return Table.Where(predicate);
}
public virtual IQueryable<T> Fetch(Expression<Func<T, bool>> predicate, Action<Orderable<T>> order)
{
var orderable = new Orderable<T>(Fetch(predicate));
order(orderable);
return orderable.Queryable;
}
}
The Orderable class
:
public class Orderable<T>
{
private IQueryable<T> _queryable;
public Orderable(IQueryable<T> enumerable)
{
_queryable = enumerable;
}
public IQueryable<T> Queryable
{
get { return _queryable; }
}
public Orderable<T> Asc<TKey>(Expression<Func<T, TKey>> keySelector)
{
_queryable = _queryable
.OrderBy(keySelector);
return this;
}
public Orderable<T> Asc<TKey1, TKey2>(Expression<Func<T, TKey1>> keySelector1,
Expression<Func<T, TKey2>> keySelector2)
{
_queryable = _queryable
.OrderBy(keySelector1)
.OrderBy(keySelector2);
return this;
}
public Orderable<T> Asc<TKey1, TKey2, TKey3>(Expression<Func<T, TKey1>> keySelector1,
Expression<Func<T, TKey2>> keySelector2,
Expression<Func<T, TKey3>> keySelector3)
{
_queryable = _queryable
.OrderBy(keySelector1)
.OrderBy(keySelector2)
.OrderBy(keySelector3);
return this;
}
public Orderable<T> Desc<TKey>(Expression<Func<T, TKey>> keySelector)
{
_queryable = _queryable
.OrderByDescending(keySelector);
return this;
}
public Orderable<T> Desc<TKey1, TKey2>(Expression<Func<T, TKey1>> keySelector1,
Expression<Func<T, TKey2>> keySelector2)
{
_queryable = _queryable
.OrderByDescending(keySelector1)
.OrderByDescending(keySelector2);
return this;
}
public Orderable<T> Desc<TKey1, TKey2, TKey3>(Expression<Func<T, TKey1>> keySelector1,
Expression<Func<T, TKey2>> keySelector2,
Expression<Func<T, TKey3>> keySelector3)
{
_queryable = _queryable
.OrderByDescending(keySelector1)
.OrderByDescending(keySelector2)
.OrderByDescending(keySelector3);
return this;
}
}
因此,可以采取以下方式:
var foos = _fooRepos.Fetch(
f => f.Name == "two" || f.Name == "three",
o => o.Asc(f => f.Name, f => f.Id)
);
难道这是我努力做到的最好办法吗? 我试图尽可能简单地这样做。 我感谢一切帮助,以及任何样本守则和文章。