NHibernate - Get a parent with a logged out child collection
I am currently working on writing a very simple online forum, and I want to get a stream with a child collection of posts to be uploaded. So my mappings:
<class name="Thread" table="ForumThreads">
<id name="Id">
<generator class="identity"></generator>
</id>
<property name="Title"></property>
<bag name="Posts">
<key column="ThreadID"></key>
<one-to-many class="Post"/>
</bag>
</class>
<class name="Post" table="ForumPosts">
<id name="Id">
<generator class="identity"></generator>
</id>
<property name="Content"></property>
<many-to-one name="Thread"
class="Thread"
column="ThreadID">
</many-to-one>
</class>
And I want to do something like this:
public class Thread
{
public virtual int Id { get; set; }
public virtual string Title { get; set; }
public virtual IEnumerable<Post> Posts { get; set; }
}
public class Post
{
public virtual int Id { get; set; }
public virtual Thread Thread { get; set; }
public virtual string Content { get; set; }
}
public Thread GetThread(int threadId, int page, int pageSize, out int count)
{
var session = SessionFactory.CurrentSession;
// Query to get the thread with a child collection of paged posts.
return thread;
}
Is it possible to do this with a single query, or will I have to split it in two?
thank
+3
source to share
2 answers
If you are thinking about doing db level paging then the approach would be something like this,
- You must use a collection to support lazy loading with extra mode
-
You may need to use a filter to load the collection (but you cannot return a stream as a result, as if you tried to access the collection it will load all messages)
public List<Post> GetThreadPosts(int threadId, int page, int pageSize, out int count) { var session = SessionFactory.CurrentSession; Thread thread = (Thread )session.Get(typeof(Thread ), threadId); var posts = session.CreateFilter(thread .Posts, "").SetFirstResult((page - 1) * pageSize).SetMaxResults(pageSize).List(); return posts ; }
0
source to share