NHibernate: CreateCriteria and Exists clause

cbp picture cbp · Nov 18, 2009 · Viewed 13.9k times · Source

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)

Answer

tolism7 picture tolism7 · Nov 18, 2009

Here is how you can do it:

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

...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>("baz")
        .SetProjection(Projections.Property("baz.FooBarId"))
        .Add(Restrictions.EqProperty("baz.FooBarId", "fooBar.Id"));

var fooBars = Session.CreateCriteria<FooBar>("fooBar")
        .Add(Subqueries.Exists(dCriteria)).List<FooBar>();