Search code examples
nhibernateexistscreatecriteria

NHibernate: CreateCriteria and Exists clause


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)

Solution

  • I worked out how to do this using the IsNotEmpty expression. Here it is using NHibernate Lambda Extensions:

    Session.CreateCriteria<FooBar>()
        .Add(SqlExpression.IsNotEmpty<FooBar>(x => x.Bazes))
        .List<FooBar>();