Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use IQueryable<T> over List<T> in LINQ to SQL [duplicate]

Possible Duplicate:
To return IQueryable<T> or not return IQueryable<T>

I have LINQ to SQL repository implemented as follows. The GetAll method is returing a generic List instead of IQueryable. However in most of the examples and tutorials pit is shown to return IQueryable. What is the advantage of returing 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();
    }


  }
}

Business Layer

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;
    }


 }
}

READING

  1. Advantage of creating a generic repository vs. specific repository for each object?
like image 997
LCJ Avatar asked Jun 21 '12 06:06

LCJ


2 Answers

Using IQueryable let LINQ move some additional work into DB by creating different SQL queries. eg. when you try something like GetAll().Where(condition) and use List all items are queried from DB and where condition is checked application-side. When you use IQueryable it can be moved to DB and proper items are returner directly from there.

like image 134
MarcinJuraszek Avatar answered Sep 18 '22 18:09

MarcinJuraszek


IQueryable extends IEnumerable. Both do not project/inflate their data until being iterated, whereas IList objects pull all their data and are populated when assigned to.

So it's a "lazy-load" vs. "eager-load" distinction.

like image 20
Tieson T. Avatar answered Sep 17 '22 18:09

Tieson T.