开发者

Caste ActiveRecord - LINQ optimised query

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开发者_JAVA百科. Because the more users I'll have, the more my query will be slow and not optimized...


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();


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜