Question

I use Castle ActiveRecord as my persistance layer.

I got this functions that must return the first 20 users from the database.

IList<User> users = new List<User>();

var userQuery = from u in User.FindAll()
                orderby u.CreationDate
                select u;

return userQuery.Take(20).ToList();

In my database, I currently have 100 users, I only want that my query return 20 users and not 100.

When I monitor what's happening with log4net, I see that the query first get 100 users and after, only take the 20 firsts.

I would like to know if it's there a better way of doing this. Because the more users I'll have, the more my query will be slow and not optimized...

Was it helpful?

Solution

This is what happens..

  1. The method User.FindAll() returns an array of all users. (100 rows from the DB)
  2. Then you order and filter that same array.

With AR 2.0 you can use ActiveRecordLinqBase instead of ActiveRecordBase and use .Queryable instead if .FindAll().

This query will return only the 20 records from the database..

var userQuery = (from u in User.Queryable
                orderby u.CreationDate
                select u).Take(20).ToList();

OTHER TIPS

Create a custom HQL query which has a "SetMaxResults" method. See the ActiveRecord Users guide for an example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top