Order by relation count in NHibernate

有些话、适合烂在心里 提交于 2019-12-19 12:12:33

问题


I have a datastructure like this:

public class User
{
    public Guid Id {get;set;}
    public string Name {get;set;}
    public IList<Books> Books {get;set}
}

I have been struggeling with making it possible to sort the users by the count of bookmarks (one-to-many relation).

I have tried various approaches with both linq, criteria and queryover, but with no luck, and therefore hope one of you could help.

I am using paging, since I have quite a few users, so the solution needs to do the query on the SQL and not in memory on the webserver.


回答1:


var loadedUser = session.Query<User>()
    .Select(u => new { u, u.Books.Count })
    .ToList()
    .OrderBy(anonym => anonym.Count)
    .Select(anonym => anonym.u);

or using HQL

select user
from User as user 
    left join user.Books as books
group by user
order by count(books)



回答2:


See : Order by collection count using ICriteria & NHibernate

select u
from User u
join u.Books b
group by u
order by count(b) asc

Or using LINQ :

users.OrderBy(x => x.Books.Count);


来源:https://stackoverflow.com/questions/6844283/order-by-relation-count-in-nhibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!