NHibernate query - Many-to-Many - eager loading (twitter style followers/following)
I have come stuck in optimizing one of my queries...here is my scenario...
I have a domain simular to Twitter where a user can follow other users. So here is a sample of my User model:
User
-> Followers (many-to-many users)
-> Following (many-to-many users)
I now need to return a paged result of users following user 'XYZ', but also eager load data needed to determine if the currently logged in user is following the returned followers.
So somehow i need to eager load this: user->followers->following
(maybe with a filter to just fetch the followi开发者_运维技巧ng
data for the current user)
Is this even possible to do in 1 query, or will I need to perform 2 seperate queries? 1 query to return the paged data of followers, then another query specifying an IN clause with returned ID's to fetch the following data for logged in user.
Paul
You need two queries to get the data, but you can execute both queries in a single trip using the NHibernate Futures methods.
In your scenario you'd do something like
var user = Session.CreateCriteria<User>()
.SetFetchMode("Followers", FethMode.Eager)
.Add(Restrictions.Eq("Id", userId)
.FutureValue<User>();
Session.CreateCriteria<User>()
.SetFetchMode("Following", FethMode.Eager)
.Add(Restrictions.Eq("Id", userId)
.FutureValue<User>();
精彩评论