为什么在LINQ to SQL中应该使用IQueryable<T>而不是List<T>?

8

可能是重复问题:
返回IQueryable<T>还是不返回IQueryable<T>

我实现了一个LINQ to SQL存储库,其中GetAll方法返回一个通用的List而不是IQueryable。但是在大多数例子和教程中,都展示了返回IQueryable的方法。返回IQueryable有什么优势呢?

using System.Linq;
namespace RepositoryLayer
{
public interface IRepository<T> where T : class
{
    //System.Linq.IQueryable<T> GetAll();
    System.Collections.Generic.List<T> GetAll();
}

public class Repository<T> : IRepository<T> where T : class
{
    public System.Data.Linq.DataContext Context
    {
        get;
        set;
    }

    //public virtual System.Linq.IQueryable<T> GetAll()
    //{
    //    //GetAll is returning generic Queryable<T>. 
    //    System.Linq.IQueryable<T> allItems = Context.GetTable<T>();
    //    return allItems;
    //}

    public virtual System.Collections.Generic.List<T> GetAll()
    {

        System.Linq.IQueryable<T> allItems = Context.GetTable<T>();
        return allItems.ToList();
    }


  }
}

业务层

namespace BusinessLayerProject
{
public class AccountBusiness
{
    //IRepository<T>
    RepositoryLayer.IRepository<RepositoryLayer.Account> accountRepository;
    public AccountBusiness(RepositoryLayer.IRepository<RepositoryLayer.Account> repo)
    {
        accountRepository = repo;
    }

    //public List<RepositoryLayer.Account> GetAllAccounts()
    //{

    //    //LibraryManagementClassesDataContext context = new LibraryManagementClassesDataContext();
    //    //List<RepositoryLayer.Account> accontList = context.Accounts.ToList();

    //    System.Linq.IQueryable<RepositoryLayer.Account> acc = accountRepository.GetAll();
    //    return acc.ToList();
    //}

    public List<RepositoryLayer.Account> GetAllAccounts()
    {
        List<RepositoryLayer.Account> acc = accountRepository.GetAll();
        return acc;
    }


 }
}

阅读

  1. 创建通用存储库与为每个对象创建特定存储库的优势是什么?

1
你应该看一下Marc Gravell在Stack Overflow上的这篇帖子,并给出答案:https://dev59.com/MHRB5IYBdhLWcg3wF0LH - Habib
1
正确,关闭机器人 - 100%重复。 - TomTom
3个回答

6

使用 IQueryable 可以让 LINQ 创建不同的 SQL 查询,将一些额外的工作移动到数据库中。例如,当您尝试类似于 GetAll().Where(condition) 的操作并使用 List 时,所有项目都会从数据库中查询,并且条件检查是在应用程序端执行的。当您使用 IQueryable 时,它可以被移动到数据库中,并且适当的项目直接从数据库返回。


1
另一个可以补充这个答案的回答是:https://dev59.com/TnE85IYBdhLWcg3wOw_s#2876655 - user170386

3

IQueryable 扩展了 IEnumerable 接口。二者在迭代之前不会投影/填充它们的数据,而 IList 对象则在赋值时立即拉取所有数据并填充。

因此,这是“延迟加载”与“立即加载”的区别。


1
感谢提供的信息。IQueryable比IEnumerable更好。IEnumerable会在数据库中执行原始查询,然后在内存中进行过滤。https://dev59.com/TnE85IYBdhLWcg3wOw_s#2876655 - LCJ

1
因为IList不够智能?
我们来看看:
如果你导出IQueryable - 在Get方法中,它是你唯一需要的方法。所有参数都进入IQueryable,并由于延迟执行最终进入你的SQL层。
导出IList,你会得到全部数据,然后再进行过滤 - 在内存中进行,这是LINQ的一种变形。
真正的诀窍在于,如果我调用你的Get方法,然后使用.Where、OrderBy,那么它就会进入数据库的SQL语句中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接