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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With