开发者

Subquery to fetch a property NHibernate

I'm using NHibernate for a web application. I have a model like this:

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() { }
}

I would like to know, how to fetch the "LastOffers" collection property with a HQL subquery ? I want to fetch it with top 10 last off开发者_如何学Cers. I have my model mapped correctly but I don't know the sintax to do a subquery fetch this property.

Today, I'm using a command like this to fetch my 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>();
        }

Thanks!


Based on description you provided I guess you need to load a set of products with preloaded lastoffers, joined to products by FK. The code below should do this:

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>();

Not testes, but idea is that we join two tables and the result will be 'collapsed' to each row of product (by DistinctRootEntityResultTransformer)

Sorry that the example is not in HQL - I prefer Criterias and QueryOver<> as more stable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜