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

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

问题描述

我知道这可能是意见,但我正在寻找最佳做法.

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

据我所知,IQueryable 实现了 IEnumerable,所以在我的 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 吗?

Should I be using IQueryable<T> here?

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

What are the pros and cons of either approach?

请注意,我计划使用 Repository 模式,因此我将拥有一个这样的类:

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 更改为 IQueryable 吗?两者有什么优点/缺点?

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 告诉调用者他们已经收到了他们请求的所有数据
  • 返回一个 IEnumerable 告诉调用者他们需要迭代结果并且它可能被延迟加载.
  • 返回一个 IQueryable 告诉调用者结果由可以处理某些类查询的 Linq 提供程序提供支持,从而将负担交给调用者以形成高性能查询.莉>
  • 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<T>从我的 DAL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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