Caste ActiveRecord - LINQ 优化查询

发布于 2024-08-12 18:45:08 字数 562 浏览 1 评论 0原文

我使用 Castle ActiveRecord 作为我的持久层。

我得到的函数必须返回数据库中的前 20 个用户。

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

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

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

在我的数据库中,我目前有 100 个用户,我只希望我的查询返回 20 个用户,而不是 100 个

。当我监视 log4net 发生的情况时,我看到查询首先获取 100 个用户,然后只获取 20 个用户。

我想知道是否有更好的方法来做到这一点。因为我拥有的用户越多,我的查询就会越慢并且没有优化......

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

醉态萌生 2024-08-19 18:45:08

这就是发生的情况。

  1. User.FindAll() 方法返回所有用户的数组。 (数据库中的 100 行)
  2. 然后您对同一数组进行排序和过滤。

使用 AR 2.0,您可以使用 ActiveRecordLinqBase 而不是 ActiveRecordBase,并使用 .Queryable 代替 if .FindAll( )。

此查询将仅返回数据库中的 20 条记录。

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

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();
调妓 2024-08-19 18:45:08

创建一个具有“SetMaxResults”方法的自定义 HQL 查询。有关示例,请参阅 ActiveRecord 用户指南

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文