我正在使用Entity Framework 4.1
和repository pattern
。首先使用實體框架代碼實現存儲庫的通用方法
我正在嘗試創建將在大多數場景中使用的方法。我正在嘗試創建一個方法,根據提供的順序標準將記錄歸併並對其進行排序。它可以按1,2或3列進行排序。我希望這個被指定。我在Orchard framework
中發現了以下代碼。
在他們下面的IRepository interface
(我離開了其他方法):
public interface IRepository<T>
{
IEnumerable<T> Fetch(Expression<Func<T, bool>> predicate);
IEnumerable<T> Fetch(Expression<Func<T, bool>> predicate, Action<Orderable<T>> order);
}
爲IEnumerable<T> Fetch(Expression<Func<T, bool>> predicate, 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;
}
}
的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)
);
這是做我想達到的最好的方式嗎?我試圖儘可能簡單。我將不勝感激所有幫助,如果有任何示例代碼和文章。
告誡反對的IQueryable:http://blog.ploeh.dk/2012/03/26/IQueryableTisTightCoupling/ –