且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我应该返回IEnumerable< T>吗?或IQueryable< T>从我的DAL吗?

更新时间:2022-04-11 14:45:36

这取决于您想要的行为.

It depends on what behavior you want.

  • 返回 IList< T> 告诉呼叫者他们已经收到了他们请求的所有数据
  • 返回 IEnumerable< T> 会告诉调用方他们需要遍历结果,并且可能会延迟加载结果.
  • 返回 IQueryable< T> 告诉调用者,结果由Linq提供程序支持,该Linq提供程序可以处理某些类的查询,从而给调用者带来了形成高性能查询的负担.
  • li>
  • Returning an IList<T> tells the caller that they've received all of the data they've requested
  • Returning an IEnumerable<T> tells the caller that they'll need to iterate over the result and it might be lazily loaded.
  • Returning an IQueryable<T> tells the caller that the result is backed by a Linq provider that can handle certain classes of queries, putting the burden on the caller to form a performant query.

尽管后者为调用者提供了很大的灵活性(假设您的存储库完全支持它),但这是最难测试的,而且不确定性最低.

While the latter gives the caller a lot of flexibility (assuming your repository fully supports it), it's the hardest to test and, arguably, the least deterministic.