我目前正在撰写一个非常基本的在线论坛,我想要检索一个包含分页帖子集的线程。所以我的映射是:
<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>
我想做这样的事情:
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;
}
是否可以使用一个查询执行此操作,或者我是否必须将其拆分为两个?
由于
答案 0 :(得分:3)
var threadId = ...
session.QueryOver<Thread>
.Where(thread => thread.Id == threadId)
.Fetch(thread => thread.Posts).Eager
.Take(pageSize)
.Skip(page)
.TransformUsing(Transformers.DistinctRootEntity)
.List<Thread>();
答案 1 :(得分:0)
如果您正在考虑进行数据库级分页,那么方法将是这样的,
您可能需要使用过滤器来加载集合,(但是您不能返回线程,因为您尝试访问集合时会加载所有帖子)
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 ;
}