Entity framework 存储库模式如何定义OrderBy
我有一个repository类,它的使用非常通用,并且没有专门引用我的表。下面显示的是获取表中所有项的函数之一。我想做的是扩展它,以便可以对结果进行排序。是否有方法传入谓词/表达式或类似的内容Entity framework 存储库模式如何定义OrderBy,entity-framework,c#-4.0,linq-to-entities,Entity Framework,C# 4.0,Linq To Entities,我有一个repository类,它的使用非常通用,并且没有专门引用我的表。下面显示的是获取表中所有项的函数之一。我想做的是扩展它,以便可以对结果进行排序。是否有方法传入谓词/表达式或类似的内容 public IQueryable<T> All<T>() where T : class { return _context.Set<T>().AsQueryable(); } public IQueryable All(),其中T:class { 返回_c
public IQueryable<T> All<T>() where T : class
{
return _context.Set<T>().AsQueryable();
}
public IQueryable All(),其中T:class
{
返回_context.Set().AsQueryable();
}
只需在所有实体上使用Queryable.OrderBy
方法即可:
fooRepository.All().OrderBy(foo => foo.Bar)
如果要添加带谓词的方法:
public IQueryable<T> AllOrderedBy<T,TKey>(Expression<Func<T,TKey>> predicate)
where T : class
{
return _context.Set<T>().OrderBy(predicate);
}
public IQueryable AllOrderedBy(表达式谓词)
T:在哪里上课
{
返回_context.Set().OrderBy(谓词);
}
顺便说一句,DbSet实现了
IQueryable
,因此您不需要调用AsQueryable()
存储库不应该返回IQueryable