问题
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