您可以从 Microsoft DynamicQuery 类中下载,这将对您有很大帮助,它使您的工作变得轻松。
http://msdn.microsoft.com/en-US/vstudio/bb964686.aspx
例如
public IEnumerable<T> GetAll<T>()
{
return this.AddIncludes(this.DbContext.Set<T>()).OrderBy (this.SortSpec.PropertyName).ToList();
}
public IEnumerable<T> Find(Expression<Func<T, bool>> expression)
{
return this.AddIncludes(this.DbContext.Set<T>()).Where(expression).OrderBy(sortingPropertyName).ToList();
}
阅读此博客:
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
将您的 Repository 模式与 UnitOfWork 模式结合起来,这将为您提供更好的抽象。
repsoistory 接口应仅包含以下重要方法:
public interface IRepository<T>
{
List<string> IncludeList { get; } // Include for EF
IEnumerable<T> GetAll<T>();
void Delete(T);
void Add(T);
IEnumerable<TEntity> Find(Expression<Func<T, bool>> expression);
}
如果您愿意,IRepository 还可以提供其他方法,例如 Any、GetRange 等。
现在问你!
I read that the IQueryable implements the IEnumerable, so. Can i create my select functions using only IQueryable return type or not???
"不同之处在于 IQueryable 是允许 LINQ-to-SQL (LINQ.-to-anything) 工作的接口。因此,如果您进一步细化 IQueryable 上的查询,该查询将在数据库中执行,如果可能的话。
对于 IEnumerable 情况,它将是 LINQ-to-object,这意味着与原始查询匹配的所有对象都必须从数据库加载到内存中。”
见:Returning IEnumerable<T> vs. IQueryable<T>