NHibernate + Criterias + DetachedCriteria

时间:2009-10-15 14:03:26

标签: nhibernate

我遇到了这个问题,我需要将这个SQL查询翻译成Criteria,但是我遇到了一些麻烦,任何人都可以帮忙吗?

SELECT * FROM Ref INNER JOIN产品生产Ref.id = Prod.id_referencia AND Prod.ProdDtAlteracao =(SELECT MAX(Prod2.ProdDtAlteracao)FROM Product Prod2 WHERE Prod.ProdCod = Prod2.ProdCod)

1 个答案:

答案 0 :(得分:0)

假设Ref有一个名为“products”的包/列表属性,它映射到Product ...

session.CreateCriteria<Ref>("r")
    .CreateAlias("products", "p", InnerJoin)
    .Add(Subqueries.PropertyEq("p.ProdDtAlteracao", DetachedCriteria.For<Product>("p2")
        .SetProjection(Projections.Max("p2.ProdDtAlteracao"))
        .Add(Restrictions.EqProperty("p.ProdCod", "p2.ProdCod"))))
    .List<Ref>();

查询看起来像

SELECT ...
    FROM Ref 
    INNER JOIN Product Prod on Ref.id = Prod.id_referencia 
    WHERE Prod.ProdDtAlteracao = (
            SELECT MAX(Prod2.ProdDtAlteracao) 
            FROM Product Prod2 
            WHERE Prod.ProdCod = Prod2.ProdCod
        )