NHibernate - 获取具有分页子集合的父级

问题描述 投票:0回答:2

我目前正在编写一个非常基本的在线论坛,我想检索带有分页帖子子集合的线程。所以我的映射是:

<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;
}

是否可以通过一个查询来完成此操作,还是必须将其分成两个?

谢谢

collections pagination nhibernate
2个回答
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>();

0
投票

如果您正在考虑进行数据库级分页,那么方法将是这样的,

  1. 你必须使用集合来支持额外模式的延迟加载
  2. 您可能需要使用过滤器来加载集合,(但您不能返回线程作为结果,就好像您尝试访问集合它将加载所有帖子一样)

    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 ;
    }
    
© www.soinside.com 2019 - 2024. All rights reserved.