2010-12-04 49 views
0

我正在使用NHibernate的Web應用程序。我有這樣一個模型:子查詢獲取屬性NHibernate

public class ProductViewModel { 
    public virtual int Id { get; set; } 
    /* others simple properties */ 

    public virtual IList<OfferViewModel> LastOffers { get; set; } 

    public ProductViewModel() { } 
} 
public class OfferViewModel { 
    public virtual string UserName { get; set; } 
    public virtual decimal Prince { get; set; } 

    public OfferViewModel() { } 
} 

我想知道,如何將「LastOffers」集合屬性與HQL子查詢取?我想用前10個最後的優惠獲取它。我有我的模型映射正確,但我不知道sintax做一個子查詢獲取此屬性。

今天,我用這樣的命令來獲取我的ViewModel:

public IList<ProductViewModel> GetProductsForSalles() 
     { 
      return 
       Session.CreateQuery(@"select p.Id as Id, 
              p.Name as Name, 
              p.Price as Price, 
              p.Price as Date 
              /* FETCH LastOffers? */ 
             from Product p 
             where p.Active=true and (p.Status=:Status) 
             order by a.Date asc") 
        .SetParameter("Status", Status.Started) 
        .SetMaxResults(50) 
        .SetResultTransformer(Transformers.AliasToBean<ProductViewModel>()) 
        .List<ProductViewModel>(); 
     } 

謝謝!

回答

1

根據您提供的描述,我想您需要加載一組帶有預加載lastoffers的產品,並由FK加入到產品中。下面的代碼應該這樣做:

return Session.CreateCriteria(typeof(ProductViewModel), "p") 
    .CreateCriteria("p.LastOffers", "lastoffers") 
    .SetResultTransformer(new NHibernate.Transform.DistinctRootEntityResultTransformer()) 
    .Add(Restrictions.Eq("p.Active", true)) 
    .Add(Restrictions.Eq("p.Status", Status.Started)) 
    .SetMaxResults(50) 
    .List<ProductViewModel>(); 

沒有睾丸,但想法是,我們在連接兩個表,結果將是「崩潰」產品的每一行(由DistinctRootEntityResultTransformer

對不起,示例不在HQL中 - 我比較喜歡Criterias和QueryOver <>更穩定。

+0

你好天才,感謝awser。實際上,DistinctRootEntityResult可以解決我的疑難問題:),但是有什麼方法可以獲取前10條記錄的屬性並通過id desc命令?我希望這可以提高性能,因爲每個產品都會有很多優惠。再次感謝! – 2010-12-06 11:38:00