NHibernate: CreateCriteria and Exists clause

前端 未结 3 804
我寻月下人不归
我寻月下人不归 2021-02-13 23:09

How can I write the following SQL using CreateCriteria:

SELECT * FROM FooBar fb
WHERE EXISTS (SELECT FooBarId FROM Baz b WHERE b.FooBarId = fb.Id)
3条回答
  •  孤街浪徒
    2021-02-13 23:55

    Here is how you can do it:

    var fooBars = Session.CreateCriteria()
            .Add(Restrictions.IsNotEmpty("Bazs")).List();
    

    ...assuming there is a collection property (one-to-many) "Bazs" in the FooBar object.

    Alternatively you could use detached criteria like that:

    DetachedCriteria dCriteria = DetachedCriteria.For("baz")
            .SetProjection(Projections.Property("baz.FooBarId"))
            .Add(Restrictions.EqProperty("baz.FooBarId", "fooBar.Id"));
    
    var fooBars = Session.CreateCriteria("fooBar")
            .Add(Subqueries.Exists(dCriteria)).List();
    

提交回复
热议问题