I am still new in entity framework. So forgive me if question is dummy 🙂
I have a domain class that get’s a list of some data from database:
public IEnumerable<Item> GetItems()
{
return context.Items.ToList();
}
This code return all items from database.
On the site I use paging so I need only 10 items per page.
So I did something like this:
var model = itemsRepository.GetItems().
Where(x => x.CategoryId == categoryId).
OrderByDescending(x => x.CreatedOnDate).
Skip(0).
Take(pageSize);
Now as I see what I did here is, I take all items from db and filter them.
Will I get some benefit if I put new method in domain and put the following code in it:
return context.Items.Where(x => x.CategoryId == categoryId).
OrderByDescending(x => x.CreatedOnDate).
Skip(0).
Take(pageSize);
Yes. You will get the benefit that your LINQ query in the latter case will get translated to SQL and executed in the database. Therefore, your first example will load the entire table into memory – while the second example will do a much more efficient query in the database.
Essentially, the
.ToList()breaks deferred execution – but it might also make sense for you to returnIQueryable<T>rather thanIEnumerable<T>, and then working on that in upper layers – depending on your requirements. Also, try reading this question and answer.