首先使用Entity框架代码实现Generic Repository
我遇到了我的关于实施框架的通用仓库模式和单位的第一次尝试。我不是在手项目中使用MVC。
请看一看这个方法包括在通用仓库等级:
I'm experiencing my first try on implementing Generic Repository Pattern and Unit of framework. I'm not using MVC on the project in hand. Please take a look at this method included in Generic Repository class:
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
它必须是一个有效的方法,并完成的目标枯井。
我的问题是,我不能为了结果作为降?任何人都可以编写一些代码行,以帮助我在这?谢谢,
it must be a powerful method and accomplishes the goal of DRY well. My problem is that, I cannot order the result as descending? Can anyone write some lines of code to help me on this? Thanks,
要按照产品类别进行筛选,试试这个:
To filter by product category, try this:
var repo = new GenericRepository<Product>();
var results = repo.Get(
p => p.Category.Name == "Foo");
下面我们声明的通用信息库的一个实例,与产品的实体类型,然后我们通过一个LAMDA表达式执行每个产品的类别名称为富的过滤。
Here we declare an instance of the Generic Repository, with an entity type of Product, then we pass a lamda expression that performs the filtering on each Product's Category whose name is "Foo".