【问题标题】:NHibernate - Get parent with paged child collectionNHibernate - 使用分页子集合获取父级
【发布时间】:2012-04-17 04:46:55
【问题描述】:

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

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

是否可以用一个查询来做到这一点,还是我必须将它分成两个?

谢谢

【问题讨论】:

标签: nhibernate collections paging


【解决方案1】:
var threadId = ...
session.QueryOver<Thread>
  .Where(thread => thread.Id == threadId)
  .Fetch(thread => thread.Posts).Eager
  .Take(pageSize)
  .Skip(page)
  .TransformUsing(Transformers.DistinctRootEntity)
  .List<Thread>();

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-13
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 2023-02-01
      • 2011-05-15
      • 1970-01-01
      相关资源
      最近更新 更多