【问题标题】:How to create read functions in a repository?如何在存储库中创建读取函数?
【发布时间】:2013-12-04 13:57:02
【问题描述】:

我正在为基本的 CRUD 操作创建一个存储库,我对读取函数有一个疑问。

我读到IQueryable 实现了IEnumerable,所以。 我可以只使用IQueryable返回类型来创建我的选择函数吗???

例子:

IQueryable<T> GetQuery() 

IEnumerable<T> GetAll()

还是只有可查询的函数?

IQueryable<T> GetAll()

谢谢!

  • 我正在使用 ASP.NET MVC5 和 EF6 :)

【问题讨论】:

  • 你可以,但为什么?您需要读取功能,因此请继续使用 IEnumerable。调用者不必知道诸如 IQueryable 之类的事情。此外,最好在退出 GetAll 方法时评估价值。

标签: c# asp.net-mvc entity-framework repository


【解决方案1】:

您可以从 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>

【讨论】:

  • 您认为更好的:public IQueryable&lt;T&gt; GetAll() &gt;&gt;&gt; return _context.DBSet&lt;T&gt;();public IEnumerable&lt;T&gt; GetAll() &gt;&gt;&gt; return _context.DBSet&lt;T&gt;().ToList();。我知道 IQueryable 它比 IEnumerable 更快,因为查询完全在服务器中运行,IEnumerable 在客户端执行查询过滤器,而 IQueryable 允许我使用 LINQ-TO-ANYTHING。所以,如果 IQueryable 比 IEnumerable 更好,为什么在我的存储库中使用 IEnumerable 作为我的读取函数,你现在明白了吗?!例如,我认为 IEnumerable 更适合数组集合。我说的对吗?
  • 是的,我同意你的看法;存储库接口不应提供 IQueryable,这将使存储库用户的生活变得困难。好的设计提供了所需的功能,就像 IEnumerable GetAll() >>> return _context.DBSet().ToList(); ((但))存储库用户必须知道这可能是昂贵的,如果执行 GetAll 他们可能会加载整个数据库。
猜你喜欢
  • 1970-01-01
  • 2020-07-08
  • 2014-02-22
  • 2011-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-23
  • 1970-01-01
相关资源
最近更新 更多