2010-05-12 27 views
4

我有一些对象:NHibernate的 - 渴望获取与已填充的孩子名单列表

Public Class Person() { 
    public int Id {get;set;} 
    public IList<Account> Accounts {get;set;} 
    public string Email {get; set;} 
} 

public class Account(){ 
    public int Id {get;set;} 
    public IList<AccountPayment> Payments {get;set;} 
    public IList<Venue> Venues {get;set;} 
} 

public class AccountPayment(){ 
    public int Id {get;set;} 
    public DateTime PaymentDate {get;set;} 
    public decimal PaymentAmount {get;set;} 
} 

public class Venue(){ 
    public int Id {get;set;} 
    public string AddressLine1 {get;set;} 
    public string Postcode {get;set;} 
} 

这些类映射到MS SQL与NHibernate - 有每类数据库的表...

我想在我的资源库中创建一个方法GetAccounts(int PersonID),它将以最有效的方式返回一个包含所有帐户的子集合的列表。任何人都可以给我任何指示如何做到这一点 - 我真的不想在我的映射中设置列表作为子选择,如果我可以帮助它...

谢谢。

+0

这篇博文解释了一种有效的方法:http://ayende.com/Blog/archive/2010/01/16/eagerly-loading-entity-associations-efficiently -with-nhibernate.aspx – 2010-05-12 13:58:08

+0

嗨迭戈,问题是我正在尝试加载Person对象的Account属性的子集合 - 我在尝试执行此操作之前查看此文章,并在第二次调查时,我仍然无法看到做到这一点的方法。我错过了什么吗? – Paul 2010-05-12 15:31:57

+0

此链接不再有效,不幸的是答案不包含任何相关信息。 – Aaronaught 2011-10-12 02:31:38

回答

0

好吧,试图做到这一点在许多不同的方式后,我终于发现,对我来说最有效的解决方案概述这个问题:

Eager loading child collection with NHibernate

我的问题上面是这是我实际遇到的挑战的一个极其简化的版本,但是使用上述方法设法使db降到2 ...从我最初的实现中获得了巨大的改进。

感谢您的帮助和指点家伙。学习了一下...

1

如果您已按照您提到的方式将类映射到表,为什么不直接调用Person对象来获取所有帐户?当您从存储库中调用Person对象时,可以急切地加载帐户。像这样:

public Person GetById(int id) 
    { 
     using (var tx = _sessionBuilder.GetSession().BeginTransaction()) 
     { 
      // -- Lazy load way -- 
      //Person person = _sessionBuilder.GetSession().Get<Person>(id); 
      //tx.Commit(); 
      //return person; 

      // -- Eager load way --     
      Person person = _sessionBuilder.GetSession().CreateCriteria<Person>() 
        .Add(Restrictions.IdEq(id)) 
        .SetFetchMode("Accounts", FetchMode.Eager) 
        .UniqueResult<Person>(); 
      tx.Commit(); 
      return person; 
     } 
    } 
+0

理想情况下,我希望加载人对象(账户支付和场所)的账户属性上的集合。我不认为上述可以做到这一点? – Paul 2010-05-12 15:03:22

+0

集合的SetFetchMode(特别是当有多个集合时)它在性能方面不是一个好主意。 – 2010-05-12 15:14:45

+0

@Paul - 我不确定FetchMode.Eager是否会嵌套集合。您可以使用NHProf查看SQL。另一种急于加载的方式,可能是在原始声明中调用存储库,并热切地致电付款和场所。 .... .SetFetchMode( “付款”,FetchMode.Eager) .SetFetchMode( “场地”,FetchMode.Eager) .... – LordHits 2010-05-12 15:55:18