我应该返回IEnumerable< T>吗?或IQueryable< T>从我的DAL吗? [英] Should I return IEnumerable<T> or IQueryable<T> from my DAL?

查看:91
本文介绍了我应该返回IEnumerable< T>吗?或IQueryable< T>从我的DAL吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这可能是一种意见,但我正在寻找最佳实践.

I know this could be opinion, but I'm looking for best practices.

据我了解,IQueryable<T>实现了IEnumerable<T>,因此在我的DAL中,我目前具有如下的方法签名:

As I understand, IQueryable<T> implements IEnumerable<T>, so in my DAL, I currently have method signatures like the following:

IEnumerable<Product> GetProducts();
IEnumerable<Product> GetProductsByCategory(int cateogoryId);
Product GetProduct(int productId);

我应该在这里使用IQueryable<T>吗?

这两种方法的优缺点是什么?

What are the pros and cons of either approach?

请注意,我正在计划使用存储库模式,因此我将拥有一个类似这样的类:

Note that I am planning on using the Repository pattern so I will have a class like so:

public class ProductRepository {

    DBDataContext db = new DBDataContext(<!-- connection string -->);

    public IEnumerable<Product> GetProductsNew(int daysOld) {
        return db.GetProducts()
          .Where(p => p.AddedDateTime > DateTime.Now.AddDays(-daysOld ));
    }
}

我应该将我的IEnumerable<T>更改为IQueryable<T>吗?彼此之间有什么优点/缺点?

Should I change my IEnumerable<T> to IQueryable<T>? What advantages/disadvantages are there to one or the other?

推荐答案

这取决于您想要的行为.

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.

这篇关于我应该返回IEnumerable&lt; T&gt;吗?或IQueryable&lt; T&gt;从我的DAL吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆