views:

179

answers:

2

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...

A: 

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

Patrick Steele
+3  A: 

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();
Sverre Ølnes
it's seems to be exactly what I want! But now, I got this error : System.ObjectDisposedException: Session is closed! Any idea how I can solve that ?
Melursus
Are you running your query inside a session-scope?When using ActiveRecord.Linq a SessionScope is required.using (new SessionScope()) { your Linq-code... }
Sverre Ølnes
Is there a way to define some sort of default Session-Scope ? Because I don't really like the idea to put a using that wrap all my linq-code..
Melursus
If your're building a web-app you should check out the SessionScopeWebModule.
Sverre Ølnes