我正在将NHibernate用于Web应用程序。我有这样的模型:
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() { }
}
我想知道,如何使用HQL子查询获取“LastOffers”集合属性?我想用前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>();
}
谢谢!
答案 0 :(得分: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&lt;&gt;更稳定。